简体   繁体   English

在匿名函数中访问它

[英]Accessing this in anonymous function

I want to create a prototype function that has its own scope. 我想创建一个具有自己范围的prototype函数。 For this, I use an anonymous function but I cannot find a way to access the members of the object. 为此,我使用匿名函数,但我找不到访问对象成员的方法。

Here is a simplified version of what I am trying to achieve: 这是我想要实现的简化版本:

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();

I know it fails because this does not refer to F or the f object. 我知道它失败了,因为这不是指Ff对象。

Is there a way to access it? 有没有办法访问它?

The immediately invoked function expression (IIFE) itself only gets invoked once, all calls to increment will use the variables as they were last left and not re- var them. 立即调用函数表达式(IIFE)本身只被调用一次,全部呼吁increment ,因为他们最后只剩会使用变量,而不是重新var他们。

Change the invocation context using call , apply or bind 使用callapplybind更改调用上下文

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

The this in this example context will not be instance specific, but be the prototype. this在这个例子情况下不会是具体的实例,但要原型。


It seems like you actually want to achieve something a little bit different, where you have an independent function to initialise an instance-specific property with it's own closure, when the instance is constructed. 看起来你实际上想要实现一些不同的东西,你有一个独立的函数来在构造实例时用它自己的闭包初始化一个特定于实例的属性。 These types of actions can consume a bit of memory so don't store too much unique data. 这些类型的操作可能会消耗一些内存,因此不要存储太多唯一数据。

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

In this example, this.increment is a different function for each instance, which means you have a different closure for each instance. 在此示例中, this.increment是每个实例的不同函数 ,这意味着每个实例都有不同的闭包。 They are generated by a function in the prototype , which sets the instance property. 它们由原型中函数生成,该函数设置实例属性。 The generator does not have to be in the prototype, just remember about the invocation context when applying it to your instance. 生成器不必在原型中,只需记住将其应用于实例时的调用上下文。

var caller = this移动到匿名函数中, this将在适当的位置设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM