我想创建一个具有自己范围的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
对象失败。
有没有办法访问它?
我想拥有特定于实例的计数器。 Kolink的版本似乎工作得很好,我明白在你的情况下,'this'将引用原型对象,它不适用于特定于实例的计数器,是吗? –
@MadEchet如果你想要一些特定的实例,你可能希望它在_constructor_中,而不是在_prototype_中。 Kolink的解决方案“有效”,因为你使用的是'caller',你可以正常使用'this',但是这个解决方案仍然在所有实例中共享'lastIncrementTime'。 –
的确如此,我没有意识到lastIncrementTime是共享的。谢谢! –