gpt4 book ai didi

javascript - 在匿名函数中访问它

转载 作者:行者123 更新时间:2023-12-02 07:02:15 24 4
gpt4 key购买 nike

我想创建一个有自己作用域的原型(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();

我知道它失败了,因为它没有引用 Ff 对象。

有没有办法访问它?

最佳答案

立即调用的函数表达式 (IIFE) 本身只会被调用一次,所有对 increment 的调用都将使用最后留下的变量,而不是重新var 他们。

使用 call 更改调用上下文, applybind

F.prototype.increment = (function() {
// this === F.prototype
// ...
}).call(F.prototype);

此示例上下文中的 this 不是特定于实例的,而是原型(prototype)。


看起来您实际上想要实现一些不同的东西,您有一个独立的函数来在构造实例时用它自己的闭包初始化特定于实例的属性。这些类型的操作会消耗一些内存,因此不要存储太多唯一数据。

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 是每个实例的不同函数,这意味着您对每个实例都有不同的闭包。它们由原型(prototype) 中的函数 生成,该函数设置实例属性。生成器不必位于原型(prototype)中,只需记住将其应用于您的实例时的调用上下文即可。

关于javascript - 在匿名函数中访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18423413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com