Javascript: how to access a class attribute from a function within one of the class functions

In my specific class function, I need to use setInterval to break the execution of the code. However, in setInterval , the "this" function no longer belongs to the "myObject" class. How can I access the variable name from the setInterval function?

 function myObject() { this.name = "the name"; } myObject.prototype.getName = function() { return this.name; } myObject.prototype.test = function() { // this works alert(this.name); var intervalId = setInterval(function() { // this does not work alert(this.name); clearInterval(intervalId); },0); } 
+4
source share
4 answers
 myObject.prototype.test = function() { // this works alert(this.name); var oThis = this; var intervalId = setInterval(function() { // this does not work alert(oThis.name); clearInterval(intervalId); },0); } 

That should work. The anonymous function "this" does not match "this" like your myObject "this".

+12
source

Here is the prototype binding function

 Function.prototype.bind = function( obj ) { var _this = this; return function() { return _this.apply( obj, arguments ); } } 
+1
source

This is what binds in Prototype:

 function myObject() { this.name = "the name"; } myObject.prototype.getName = function() { return this.name; } myObject.prototype.test = function() { // this works alert(this.name); var intervalId = setInterval(function() { // this does not work alert(this.name); clearInterval(intervalId); }.bind(this),0); } 
0
source

Please note that s13james answer is incomplete in that bind() not a standard function and should be provided elsewhere - one way uses the prototype.js Javascript structure and the other is to do it yourself using the meouw code example.

If you are not using bind() (this is elegant, I have to say), then djangel's answer is what you could do, and this is what I most often do.

0
source

All Articles