2011-09-03 15 views
1

我有一個全局變量,稍後在我的程序中更新,而前一個變量設置爲全局變量使用原始引用值。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方法,它存儲的參考當時認爲值,從而不會返回更新後的值

回答

1

你可以把的testvar成一個對象,因爲對象是通過JS引用傳遞,這樣你就不會需要調用一個函數來獲取最新的值:

var testVar = {'value':123}; 

var hash = { 
    test : { 
     testGetVar : testVar, 
     testGetVarFn : function(){ return testVar; } 
    } 
} 

testVar.value='abc'; 
console.log(hash.test.testGetVar.value); // returns 123 (not anymore: returns "abc" now) 
console.log(hash.test.testGetVarFn().value); //returns abc 
+0

你的意思是放在你的console.log中,分別是'hash.test.testGetVar.value'和'hash.test.testGatVarFn().value'。它會在你的版本中返回'[object Object]'。 – 0x499602D2

+0

謝謝! -answer updated :) – stewe

+0

+1,因爲這是一種解決方法。 – 0x499602D2

1
var a = "Hello", 
    b = a; 

a = "Goodbye"; 

console.log(b); // "Hello" 

既然你調用函數,它會尋找最新版本的testVartestGetVar屬性的值將保持不變,除非在程序中稍後進行更改。所以是的,你必須明確更新hash.test.testGetVar的值,或者只需調用函數testGetVarFn

+0

所以我必須寫一個函數每次以獲得最新的價值? – tamade

+0

檢查編輯:是,或者自己更新'hash.test.testGetVar'的值。 – 0x499602D2

2

我想你是問如何將引用複製到整數。 Javascript不支持指針,所以我相信它只能在閉包中完成,比如你的例子中的函數。但請注意,對象默認通過引用傳遞。

還有就是這裏傳遞參數時,按值/按引用規則的一個很好的說明:

http://docstore.mik.ua/orelly/web/jscript/ch09_03.html