綁定這一個嵌套函數我有一個關於在Underscore.js 的綁定特徵的問題,讓我們說我們有以下的對象「房間」:與Underscore.js
var person = 'Bob';
$(function() {
var room = {
capacity: 10,
exits: 2,
count: 0,
person: '',
addPerson: function (name) {
this.count += 1;
var nestedFunction = function (nameOfPerson) {
// this is bound to window
this.person = nameOfPerson;
}(name);
}
};
room.addPerson('dave');
});
在在我的評論中指出的那一行,「this」是綁定在窗口上的。這是預期的行爲。
比方說,我們要綁定它的「房間」對象。用Underscore.js的bind方法可以做到嗎?
注:我知道我可以處理這與老「這=這個」例程。但我對此不感興趣。
+1但是,'nestedFunction.call'將不起作用,因爲IIFE的結果分配給它,而不是函數本身。 – thefourtheye
謝謝@thefourtheye。其實,我已經更新了代碼片段,它不再是'IIFE'。該代碼位於下面的JSFIDDLE鏈接中。 –
但OP的代碼只有IIFE – thefourtheye