I want to create a prototype
function that has its own scope. 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.
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.
Change the invocation context using call
, apply
or bind
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.
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. 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
将在适当的位置设置。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.