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

标签 javascript

我正在创建一个 JavaScript 对象,并且希望能够被动地检测传入对象中的更改。

我尝试使用代理对象,但无法重现所需的行为。我尝试在代码中实现的一个示例是:Listening for variable changes in 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);

}

关于JavaScript 构造函数监听此变量更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137538/

相关文章:

javascript - 在 asp.net 文本框中检查脚本

javascript - 根据 PDF 文档中的页数,通过自定义命令 (Javascript) 调用操作项(手动创建)

javascript - node.js/从响应写入文件

javascript - 如何在没有声明文件的情况下从其他js文件扩展类

javascript - 使 Javascript 正则表达式不区分大小写

javascript - 验证 id 是否存在在 Firebase 中被忽略

javascript - 使用 getElementsByTag 更改表中的值

javascript - 从数组中删除有副作用

javascript - Angular 库导入 *

javascript - 递归函数中的 for in 循环未完成