Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  138] [ 2]  / answers: 1 / hits: 36229  / 13 Years ago, tue, october 25, 2011, 12:00:00

Normally I'd assign an alternative self reference when referring to this within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.



function Foo() {}
Foo.prototype = {
bar: function () {
this.baz();
},
baz: function () {
this.draw();
requestAnimFrame(this.baz);
}
};

More From » scope

 Answers
6

Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either


Wrap the method call inside an anonymous function


This way, accessing the baz property and calling it happen at the same time, which is necessary for the this to be set correctly inside the method call.


You will need to save the this from the outer function in a helper variable, since the inner function will refer to a different this object.


var that = this;
setInterval(function(){
return that.baz();
}, 1000);

Wrap the method call inside a fat arrow function


In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:


setInterval( () => this.baz(), 1000 );

Fat arrow anonymous functions preserve the this from the surrounding function so there is no need to use the var that = this trick. To see if you can use this feature, consult a compatibility table like this one.


Use a binding function


A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.


setInterval( this.baz.bind(this), 1000 );

//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);

[#89455] Sunday, October 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;