[英]Accessing this in anonymous function
我想創建一個具有自己范圍的prototype
函數。 為此,我使用匿名函數,但我找不到訪問對象成員的方法。
這是我想要實現的簡化版本:
function F() {
this.counter = 0;
}
F.prototype.increment = (function() {
var lastIncrementTime = -1;
var caller = this; // <--- it fails here because this is the Window object
return function(time) {
if (time > lastIncrementTime) {
caller.counter++;
lastIncrementTime = time;
return caller.counter;
}
return caller.counter;
}
})();
f = new F();
f.increment();
我知道它失敗了,因為這不是指F
或f
對象。
有沒有辦法訪問它?
該立即調用函數表達式(IIFE)本身只被調用一次,全部呼吁increment
,因為他們最后只剩會使用變量,而不是重新var
他們。
F.prototype.increment = (function() {
// this === F.prototype
// ...
}).call(F.prototype);
在this
在這個例子情況下不會是具體的實例,但要原型。
看起來你實際上想要實現一些不同的東西,你有一個獨立的函數來在構造實例時用它自己的閉包初始化一個特定於實例的屬性。 這些類型的操作可能會消耗一些內存,因此不要存儲太多唯一數據。
function F() {
this.counter = 0;
this.__init_increment(); // create `this.increment`
}
F.prototype.__init_increment = function () {
var lastIncrementTime = -1;
this.increment = function (time) {
if (time > lastIncrementTime) {
this.counter++;
lastIncrementTime = time;
}
return this.counter;
};
};
var f = new F();
f.increment(0); // 1
f.increment(0); // 1
f.increment(5); // 2
在此示例中, this.increment
是每個實例的不同函數 ,這意味着每個實例都有不同的閉包。 它們由原型中的函數生成,該函數設置實例屬性。 生成器不必在原型中,只需記住將其應用於實例時的調用上下文。
將var caller = this
移動到匿名函數中, this
將在適當的位置設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.