我可以根据对另一个变量的更改来设置变量的值吗? [英] Can I make a variable's value depend on changes to another variable?

查看:70
本文介绍了我可以根据对另一个变量的更改来设置变量的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript变量 a 和一个变量 b ,其值可以是0或1。 / p>

任何人都可以建议我如何编码函数,因此 b 可能取决于的值a 是这样的:




  • a 从0到1 - 如果 code>为超过 500毫秒,则 b 设置为1

  • a 从1更改为0时 - b 设置为0 立即



如果有办法使用函数对此进行编码,那么可以将其附加到变量 a 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;
}
});

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

  //立即设置为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);

这篇关于我可以根据对另一个变量的更改来设置变量的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆