2015-06-19 24 views
1

深對象內訪問功能我有一個對象的Javascript:在解析

var object1 = { 
 
    object2: { 
 
    function1: function(a, b, c, d, e) { 
 
     //do some stuff with those parameters 
 
     console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d); 
 
    }, 
 
    function2: object1.object2.function1(2, 3, 4, 5) 
 
    } 
 
}

爲什麼行function2: object1.object2.function1(2, 3, 4, 5)線拋出Uncaught TypeError: Cannot read property 'object2' of undefined,我怎樣才能使這項工作?

更新:答案已標記。

謝謝

+3

'object1'和' object1.object2'在您嘗試調用'object1.object2.function1(...)'時未完全構建。因此錯誤。 – techfoobar

+0

你試圖用這個對象結構來解決什麼樣的問題,或者你只是在試驗? – Andy

+0

可能重複[在對象字面聲明中的自引用](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) –

回答

1

因爲在function2定義不包含object1的定義範圍。然後,當您嘗試訪問object1.object2它拋出錯誤,因爲object1沒有定義

+0

另外,只有在調用時,對象纔會在解析時構建。 – thednp

1

下面將工作:

var object1 = { 
 
    object2: { 
 
    function1: function(a, b, c, d, e) { 
 
     //do some stuff with those parameters 
 
     console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d); 
 
    }, 
 
    function2: function(a, b, c, d, e) { 
 
     object1.object2.function1(2, 3, 4, 5); 
 
    } 
 
    } 
 
} 
 
object1.object2.function2();

基本上在要撥打object1時間它還不存在。這是你得到這個錯誤的原因。我只是通過將其插入函數並稍後明確地調用它來延遲這一點。

請注意,JavaScript沒有參數檢查,只是失敗,如果他們不匹配。

+0

注意:不使用函數2參數 –

1
var object1 = { 
    object2: { 
     function1: function (a, b, c, d, e) { 
      //do some stuff with those parameters 
      console.log('values are ' + a + ' ' + b + ' ' + c + ' ' + d); 
     }, 
     function2: function() { this.function1(2, 3, 4, 5); return this; } 
    }.function2() 
} 
object1.object2.function1(9, 8, 7, 6, 5); 
1

如果你想function2速記爲function1調用預定義參數,您可以使用bind

object1.object2.function2 = object1.object2.function1.bind(null, 2, 3, 4, 5) 

,如果你需要的上下文,更換nullobject1.object2

+0

這似乎很有用。謝謝。 – thednp