[removed] How do constantly monitor variables value

前端 未结 6 2386
无人共我
无人共我 2021-02-14 08:36

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 09:05

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

提交回复
热议问题