我有一個全局變量,稍後在我的程序中更新,而前一個變量設置爲全局變量使用原始引用值。Javascript正確引用值
爲了說明,
var testVar = 1;
var hash = {
test : {
testGetVar : {opacity: testVar},
testGetVarFn : function(){ return {opacity: testVar}; }
}
}
testVar = 2;
console.log(hash.test.testGetVar.opacity); // returns 1
console.log(hash.test.testGetVarFn().opacity); //returns 2
會有人澄清適當的方式做到這一點? 假設我有10個使用testVar的哈希對象,我需要寫fn來獲取更新的值嗎?
編輯: 我已經改變了一些要求,並使我的例子具體到我的原因。
這裏是getter/setter方法,但不起作用。
var testVar = new Field("123");
function Field(val){
this.value = val;
}
Field.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
var hash = {
test : {
testGetVar : {opacity: testVar.value} ,
testGetVarFn : function(){ return testVar.value; }
}
}
testVar.value = "abc";
console.log(hash.test.testGetVar.opacity); // returns 123
console.log(hash.test.testGetVarFn()); //returns abc
我的假設是因爲創建哈希時調用get方法,它存儲的參考當時認爲值,從而不會返回更新後的值
你的意思是放在你的console.log中,分別是'hash.test.testGetVar.value'和'hash.test.testGatVarFn().value'。它會在你的版本中返回'[object Object]'。 – 0x499602D2
謝謝! -answer updated :) – stewe
+1,因爲這是一種解決方法。 – 0x499602D2