2010-06-16 58 views

回答

12

Ehm?

var testVariable = 10; 
var oldVar = testVariable; 

... 
if (oldVar != testVariable) 
alert("testVariable has changed!"); 

沒有,也沒有神奇的 「var.hasChanged()」,也不是 「var.modifyDate()」 在Javascript除非你自己編寫的。

1

如果你是一個Firefox用戶,你可以檢查使用螢火蟲。如果您使用IE,我們可以放置警報語句並檢查變量的值。

-1

通過將其與已知狀態進行比較來查看它是否有所不同。如果你正在尋找類似variable.hasChanged的東西,我敢肯定,這不存在。

4

還有就是要觀察變量更改的方式: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'); 
+0

IE和Safari不支持。 – bezmax 2010-06-16 08:09:22

1

一些代碼使用getterssetters

var _variable; 
get variable() { 
    return _variable; 
} 
set variable(value) { 
    _variable = value; 
    // variable changed 
} 

,或者如果你不需要變量的值稍後:

set variable(value) { 
    // variable changed 
}