【问题标题】:How to observe any variable changes (any variable and not only Object)?如何观察任何变量的变化(任何变量而不仅仅是对象)?
【发布时间】:2021-02-13 21:50:39
【问题描述】:

在 Ecma6 中,现在可以很容易地观察 Object 的变化,这要归功于 Proxy

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

我正在寻找一种方法来观察任何变量(不仅是对象,还有 int、String..)

例如:

let s = "hello";
s = "world"; // should trigger an event when telling me that s has changed
let x=1;
x = 2; //should trigger an event when telling me that x has changed
let o = {"foo":"bar};
o.foo = "bar2"; //should trigger an event when telling me that o has changed 

使用 defineProperty 找到了一些线索,但无法将其应用于“let”变量

Listening for variable changes in JavaScript

【问题讨论】:

  • 在 JS 中不可能。
  • 你只能通过预处理源代码来做到这一点,例如检测/检测任何变量赋值。 Svelte 就是这样做的(虽然我不知道细节)。
  • 强 XY 问题。这有什么好处?

标签: javascript ecmascript-6


【解决方案1】:

为了完整起见,我觉得值得分享的是,您要求的至少某些功能在技术上是可行的,但我强烈建议探索不同的功能解决您遇到的潜在问题的方法。

不建议使用with 语句,因为它可能是混淆错误和兼容性问题的根源。

使用with 语句和Proxy,可能会捕获分配,因为您实际上是在拦截对添加到作用域中的Environment Record 的操作。然而,使用let 声明,这是绝对不可能的。

const handler = {
  has(target, key) {
    return typeof key === 'string';
  },
  set(target, key, value) {
    console.log(key, 'has changed');
    switch (typeof value) {
      case 'function':
      case 'object':
        value = new Proxy(value, handler);
    }
    return Reflect.set(target, key, value);
  }
};

with (new Proxy(Object.create(null), handler)) {
  s = 'world';
  x = 2;
  o = { foo: 'bar' };
  o.foo = 'bar2';
  let v = []; // not trapped
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多