2014-02-11 112 views
0

爲了更好的代碼結構,我想用一個JavaScript對象持有的所有屬性,而不是使用多個瓦爾:創建一個變種對象VS多個變種

// 1. WAY 
// This returns an error, as _inp cannot be accessed by input_value 
// Uncaught TypeError: Cannot read property 'value' of undefined 
var ref = { 
_inp: input.target, 
input_value: _inp.value, 
.... 
}; 

// 2. WAY 
// When using this, it works 
var ref = { 
_inp: input.target, 
input_value: input.target.value, 
.... 
}; 


// 3. WAY 
// This obviously works, too. 
var 
    _inp = input.target, 
    input_value = _inp.value, 

我的問題是,爲什麼3路工程和1 。不會嗎?

+0

你應該在這個看一看,瞭解你的JavaScript的數據類型,HTTP:// WWW .oreillynet.com /酒吧/ A/JavaScript的/摘錄/學習的JavaScript/javasc ript-datatypes-variables.html – gmaliar

回答

3

在示例1中,_inp將是對象的屬性。這不是一個變量。您只能從對該對象的引用訪問它(並且它不會是對象的屬性,直到對象存在,這將在對對象文字進行求值後,另請參閱Self-references in object literal declarations)。

+0

非常有用的鏈接到另一個StackOverflow問題與一些相當有趣的解決方案。 – Xuntar

+0

是的,該鏈接幫助我。以下解決方案的工作原理:\t(溶液1)VAR REF = { \t \t \t \t \t \t \t _inp:input.target, \t \t \t \t \t \t \t將input_value:空, \t \t \t \t \t \t INIT:功能(){ \t \t \t \t \t \t this.input_value = this._inp.value; \t \t \t \t \t \t return this; \t \t \t \t \t \t} \t \t \t \t \t \t}的.init(); \t \t \t \t \t \t \t \t(溶液2:優選的)VAR REF = { \t \t \t \t \t \t _inp:輸入。目標, \t \t \t \t \t \t GET將input_value(){ \t \t \t \t \t \t \t回報this._inp.value; \t \t \t \t \t \t} \t \t \t \t};我更喜歡解決方案2.但是,我想出於性能原因,最好使用多個變量而不是一個對象創建(請參閱3.WAY)。 – nimo23

1

因爲_inp只會在通過整個var ref = { ... };聲明後填入input.target值。這意味着當你嘗試使用它時,它還不存在。

0

第一種方式不起作用,因爲您引用的「_inp」不是現有的變量。和裁判對象沒有完全建立(這就是爲什麼input_value: this._inp.value也不工作)

創建對象和其屬性分配值,你可以使用函數(我把大部分代碼):

var ref = { 
    _inp: input.target, 
    input_value: null, 
    init: function() 
    { 
    this.input_value = this._inp.value; 
    } 
}; 
ref.init(); 
console.log(ref.input_value); // will contains the same as input.target.value 

,但通常情況下,人們創造與默認值的所有屬性的對象,並傳遞一個參數傳遞給他們的初始化函數:

var ref = { 
    _inp: null, 
    input_value: null, 
    init: function(input) 
    { 
    if (input) 
    { 
     this._inp  = input.target; 
     this.input_value = input.target.value; 
    } 
    } 
}; 
var input = {target:{value:"foo"}}; 
ref.init(input); 
+0

是的,這是我做到這一點。謝謝! – nimo23

相關問題