JavaScript 构造函数侦听此变量更改



>我正在创建一个JavaScript对象,并希望能够反应性地检测传入对象中的更改。

我尝试使用代理对象,但无法重现所需的行为。我尝试在代码中实现的一个例子是:侦听JavaScript中的变量变化

这是我使用的构造函数的非常基本的外壳:

function Fluid(options) {
    this.options = options;
    // Here is where I use the options object, and would like to be able to re-evaluate certain pieces of code if any values in 'this.options' changes.
}
let myApp = new Fluid({
    testValue: 1
});

我的预期输出可能是这样的:

function Fluid(options) {
    this.options = options;
    function doThings() {
        if(this.options.testValue === 1) {
            console.log("The value is 1");
        } else {
            console.log("The value is not 1");
        }
    }
    doThings();
    // Here I would implement the code to detect changes in the this.options object, and if this.options changes, I can execute a function, like doThings()
}
let myApp = new Fluid({
   testValue: 1
});
// Console: The value is 1
myApp.testValue = 2;
// Console: The value is not 1

在使更多代理对象过期后,我能够使用以下代码解决此问题:

function Fluid(options) {
    this.options = options;
    let proxyHandler = {
        set: (target, objectKey, value) => {
            console.log(`Setting property "${objectKey}" = "${value}"`);
            return target[objectKey] = value;
        }
    };
    this.options = new Proxy(this.options, proxyHandler);
}

最新更新