Can I make a variable's value depend on changes to another variable?

こ雲淡風輕ζ 提交于 2020-01-03 05:52:16

问题


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 ?


回答1:


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



回答2:


This is how I'd do it, just define a toggleA function that has access to the outer scope:

var a = 0, b, t,
toggleA = function() {
  switch(a) {
    case 0:
      a = 1;
      t = window.setTimeout(function(){ b = 1; }, 500);
      break;
    case 1:
      window.clearTimeout(t);
      a = b = 0;
      break;
  }
};

Calling toggleA() will switch as value between 1 and 0. Depending on how long it takes to switch the value of a from 1 to 0, the value of b may also be changed.



来源:https://stackoverflow.com/questions/23692174/can-i-make-a-variables-value-depend-on-changes-to-another-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!