如何为现有对象设置通用 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 的说明。