微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何为现有对象设置通用 getter? 示例

如何解决如何为现有对象设置通用 getter? 示例

我有兴趣添加通用 getter,它会在现有对象的每个属性 get 调用上执行。 我们都知道如何为特定属性设置getter,但是我们可以设置getter,在获取对象中的每个属性时会涉及回调吗?

非常感谢。

解决方法

我认为您在考虑 Proxy

具体来说,您可以使用 handler.get() 拦截任何属性。

示例

const guitar = {
  stringCount: 6,model: 'Stratocaster',};

// this is where the magic happens
const genericHandler = {
  get: function(target,propertyName) {
    // at this point,you can do anything you want – we'll just log the attempt
    console.log(`Attempted to get ${propertyName}`);

    // this will return the original value
    return target[propertyName];
  }
};

const proxiedGuitar = new Proxy(guitar,genericHandler);

// This outputs
//   Attempted to get stringCount
//   6
console.log(proxiedGuitar.stringCount);

// you can even write a handler for non-existent properties
console.log(proxiedGuitar.pickupType);

这是一个简化且不完整的示例,在某些情况下可能不起作用。请参阅下面评论中@loganfsmyth 的说明。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。