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

纵饮孤独 提交于 2019-12-10 09:32:05

问题


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

回答1:


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."




回答2:


Here's the prototype bind function

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



回答3:


This is what binding is for 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);
}



回答4:


Please note that s13james's answer is incomplete in that bind() is not a standard feature and must be provided elsewhere - one way is using the prototype.js Javascript framework, while another will be to do it yourself using meouw's code example.

If you don't use bind() (which is nifty, I must say) then djangel's response is what you could have done, and is what I most often do.



来源:https://stackoverflow.com/questions/429487/javascript-how-to-access-a-class-attribute-from-a-function-within-one-of-the-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!