且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以根据对另一个变量的更改来设置变量的值吗?

更新时间:2023-01-24 17:35:21

如果可以,请用 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;
}
});

然后,您可以像这样使用它:

  //立即设置为0 
obj.a = 0;
console.log(obj.b);

//设置为1并开始超时
obj.a = 1;
console.log(obj.b);
setTimeout(function(){
console.log(obj.b);

//设置回0
obj.a = 0;
console.log(obj.b);

//嘿,确保更改止损b设置为
obj.a = 1;
obj.a = 2;
setTimeout(function(){
console.log(obj.b);
},500);
},500);


I have a javascript variable a and a variable b that can have a value of 0 or 1.

Can anyone suggest how I could code a function sob could depend on the value of a like this:

  • When a changes from 0 to 1 - if a is 1 for more than 500ms then b is set to 1
  • When a changes from 1 to 0 - b is set to 0 immediately

If there's a way to code this using a function then could that be attached to the variable a's setter ?

If you can, wrap the access with 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;
    }
});

Then, you can use it like so:

// 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);