Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to access a class attribute from a function within one of the class's functions

Within my a certain function of a class, I need to use setInterval to break up the execution of the code. However, within the setInterval function, "this" no longer refers to the class "myObject." How can I access the variable "name" from within 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);
}
like image 395
Chris B Avatar asked Dec 14 '22 05:12

Chris B


1 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);
}

This should work. The anonymous function's "this" is not the same "this" as your myObject's "this."

like image 104
jacobangel Avatar answered Dec 15 '22 18:12

jacobangel