是,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;
這是非常方便和可讀。
'mootools'的方式是使用.each(api)而不是.forEach(不在舊的ie中)。 fn之後的第二個arg是上下文。但是'self = this'是大多數人的首選。 – 2013-02-14 02:04:45
啊是的,我甚至沒有注意到forEach ......你最正確的使用'self = this'方法。我對綁定感到情有獨鍾,尤其是因爲當時我的頭很困難。 – Boris 2013-02-14 09:55:31
儘管這個方法仍然有效,但是我刪除了所有的錯誤:) – Boris 2013-02-14 09:57:11