2013-02-13 46 views
3

什麼是訪問testval的最佳方式testoption在foreach循環中?這是一個mootools草案。在每個循環內訪問'this'對象屬性

var some = new Class({ 
    options: { testarray: [1,2,3], testoption: 6 },  
    initialize: function(options) { 
     this.testval = '123'; 
     this.options.testarray.each(function(el) { 
     console.log(this.testval); 
     console.log(this.options.testoption); 
     }); 
    } 
}); 

UPDATE: 我可以通過添加陣列上綁定(本)修復它,但就是要走的路?

回答

3

如果我需要從函數中引用一些實例變量,使得this引用其他內容,我經常在前面使用var self = this;。我發現它比整個地方都有約束力。 self變得明確指出實例。

2

是,MooTools的方式做到這一點是綁定你的函數或者與

this.options.testarray.each(function(el) { 
    console.log(this.testval); 
    console.log(this.options.testoption); 
}.bind(this)); 

或使用Binds突變

var some = new Class({ 
options: { testarray: [1,2,3], testoption: 6 }, 
Implements: Optons, 
Binds: ['logOption'], 
initialize: function(options) { 
    this.testval = '123'; 
    this.setOptions(options); 
    this.options.testarray.each(this.logOptions); 
}, 
logOptions : function(value, index, array) { 
    // I don't really see the point, but here you are, this code will be executed 
    // three times, with (1, 0, [1,2,3]), (2, 1, [1,2,3]) and (3, 2, [1,2,3]) 
    console.log(value, index, array); 
    console.log(this.testval); 
    console.log(this.options.testoption); 
} 
}); 

(在Mootools的更多,感謝@Dimitar克里斯托夫提供)我在initialize()中移動了你的每一個(而不是forEach,如評論中所說),因爲我不確定類描述符對象mill工作內的代碼是什麼......你也可能想用initialize this.setOptions(options)並執行該選項這個變種人。

此外,正如每個評論中指出,你有var self = this;這是非常方便和可讀。

+0

'mootools'的方式是使用.each(api)而不是.forEach(不在舊的ie中)。 fn之後的第二個arg是上下文。但是'self = this'是大多數人的首選。 – 2013-02-14 02:04:45

+0

啊是的,我甚至沒有注意到forEach ......你最正確的使用'self = this'方法。我對綁定感到情有獨鍾,尤其是因爲當時我的頭很困難。 – Boris 2013-02-14 09:55:31

+0

儘管這個方法仍然有效,但是我刪除了所有的錯誤:) – Boris 2013-02-14 09:57:11