gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:16:41 25 4
gpt4 key购买 nike

我正在创建一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com