Javascript:如何持续监控变量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4631896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:21:46  来源:igfitidea点击:

Javascript: How do constantly monitor variables value

javascriptvariableswebkitmonitor

提问by Connor

How do I constantly check a variables value. For example:

我如何不断检查变量值。例如:

if(variable == 'value'){
    dosomething();
}

This would work if I constantly looped it or something, but is there an efficient way of triggering that as soon as the variable is set to that value?

如果我不断循环它或其他东西,这会起作用,但是一旦变量设置为该值,是否有一种有效的方法来触发它?

回答by Mike Samuel

Object.watch:

Object.watch

Watches for a property to be assigned a value and runs a function when that occurs.

监视要分配值的属性并在发生时运行函数。

Object.watch() for all browsers?talks about cross-browser ways to do Object.watchon browsers that don't support it natively.

Object.watch() 适用于所有浏览器?谈论跨浏览器Object.watch在本地不支持它的浏览器上的方法。

回答by K2Spam

Object.defineProperty(Object.prototype, 'watch', {
    value: function(prop, handler){
        var setter = function(val){
            return val = handler.call(this, val);
        };
        Object.defineProperty(this, prop, {
            set: setter
        });
    }
});

How to use:

如何使用:

var obj = {};

obj.watch('prop', function(value){
    console.log('wow!',value);
});

obj.prop = 3;

回答by Jacob

As @Pekka commented, you can have a timer constantly poll the variable. A better solution, if it's all your code that's changing the variable, is to not just set the variable directly, but rather have all setters call a function. The function could then set the variable and do any additional processing you need.

正如@Pekka 评论的那样,您可以让计时器不断轮询变量。一个更好的解决方案,如果你的所有代码都在改变变量,那么不仅仅是直接设置变量,而是让所有的 setter 调用一个函数。然后该函数可以设置变量并执行您需要的任何其他处理。

function setValue(value) {
    myVariable = value;
    notifyWatchers();
}

回答by goat

If you encapsulate your variable so that the value can only be set by calling a function, it gives you the opportunity to check the value.

如果您封装变量以便只能通过调用函数来设置值,那么您就有机会检查该值。

function ValueWatcher(value) {
    this.onBeforeSet = function(){}
    this.onAfterSet = function(){}

    this.setValue = function(newVal) {
        this.onBeforeSet(value, newVal)
        value = newVal;
        this.onAfterSet(newVal)
    }
    this.getValue = function() {
        return value;
    }
}

var name = new ValueWatcher("chris");

wacthedName.onBeforeChange = function(currentVal, newVal) {
    alert("about to change from" + currentVal + " to " + newVal);
}

name.setValue("Connor");

回答by Chandu

Use setInterval:

使用 setInterval:

var key = ''
setInterval(function(){
  if(key == 'value'){
    dosomething();
  }
}, 1000);