【问题标题】:How I can set general getter for an existing object?如何为现有对象设置通用吸气剂?
【发布时间】:2021-08-17 01:36:49
【问题描述】:

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

非常感谢。

【问题讨论】:

  • 您需要一个Proxy。
  • 如果它明确需要使用现有对象,那么这是不可能的。代理可以做到这一点,但需要一个新对象,而且代理非常复杂,在我看来通常不是一个好主意。
  • 你希望 getter 做什么?

标签: javascript object ecmascript-6 default-value ecmascript-next


【解决方案1】:

我认为您正在考虑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 的说明。

【讨论】:

  • 这是一个糟糕的get 处理程序。 get 传递了 3 个参数,因此您应该使用 Reflect.get 查找要返回的属性。这也是一个不完整的代理膜,所以你应该提到这在很多情况下都会破坏,比如guitar 对象存储在弱映射中或者是使用私有类属性的类。
  • @loganfsmyth 感谢您的澄清!你说得对。我的意图确实不是提供可用于生产的代码(尽管这可能是该网站的许多用户所期望的......),只是对一个简单问题的简单回答——介绍代理的概念 .
猜你喜欢
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2019-09-27
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
相关资源
最近更新 更多