变量值是否发生了变化

Nir*_*bey 3 javascript

如何在javascript中查找变量值是否发生变化.

bez*_*max 12

埃姆?

var testVariable = 10;
var oldVar = testVariable;

...
if (oldVar != testVariable)
alert("testVariable has changed!");
Run Code Online (Sandbox Code Playgroud)

不,除非你自己编写代码,否则Javascript中没有神奇的"var.hasChanged()"和"var.modifyDate()".


meo*_*ouw 5

有一种方法可以观察变量的变化:Object::watch- 下面的一些代码

/*
For global scope
*/

// won't work if you use the 'var' keyword
x = 10;

window.watch( "x", function( id, oldVal, newVal ){
    alert( id+' changed from '+oldVal+' to '+newVal );

    // you must return the new value or else the assignment will not work
    // you can change the value of newVal if you like
    return newVal;
});

x = 20; //alerts: x changed from 10 to 20


/*
For a local scope (better as always)
*/
var myObj = {}

//you can watch properties that don't exist yet
myObj.watch( 'p', function( id, oldVal, newVal ) {
    alert( 'the property myObj::'+id+' changed from '+oldVal+' to '+newVal );
});


myObj.p = 'hello'; //alerts: the property myObj::p changed from undefined to hello
myObj.p = 'world'; //alerts: the property myObj::p changed from hello to world

// stop watching
myObj.unwatch('p');
Run Code Online (Sandbox Code Playgroud)