我有一个 javascript 变量 a
和一个变量 b
,每个变量的值可以为 0 或 1。
任何人都可以建议我如何实现一个设计,以便 b
将根据以下规则取决于 a
的值:
- 当
a
从 0 变为 1 时 - 如果a
为 1 的时间超过 500 毫秒,则b
为设置为 1 - 当
a
从1变为0时 -b
立即设置为0
如果有一种方法可以使用函数对其进行编码,那么可以将其附加到变量a's
setter吗?
最佳答案
如果可以,请使用 defineProperty
包装访问:
var obj = {
_a: 1
};
Object.defineProperty(obj, "a", {
get: function() {
return this._a;
},
set: function(newA) {
if (this.changeB) {
clearTimeout(this.changeB);
this.changeB = null;
}
if (this.a == 0 && newA == 1) {
this.changeB = setTimeout(function() {
this.b = 1;
}.bind(this), 500);
}
else if (this.a == 1 && newA == 0) {
this.b = 0;
}
this._a = newA;
}
});
然后,您可以像这样使用它:
// Immediately set to 0
obj.a = 0;
console.log(obj.b);
// Set to 1 and start the timeout
obj.a = 1;
console.log(obj.b);
setTimeout(function() {
console.log(obj.b);
// Set back to 0
obj.a = 0;
console.log(obj.b);
// And hey, make sure changing a stops b from being set
obj.a = 1;
obj.a = 2;
setTimeout(function() {
console.log(obj.b);
}, 500);
}, 500);
关于javascript - 我可以使一个变量的值取决于另一个变量的更改(有时在延迟后)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23692174/