[removed] How do constantly monitor variables value

前端 未结 6 1144
青春惊慌失措
青春惊慌失措 2021-02-14 08:35

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

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

This would work if I constantly loope

6条回答
  •  耶瑟儿~
    2021-02-14 08:59

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

提交回复
热议问题