Javascript:如何从类的一个函数中的函数访问类属性

Chr*_*s B 4 javascript oop class-design

在我的某个类的某个函数中,我需要setInterval用来分解代码的执行.但是,在setInterval函数中,"this"不再引用类"myObject".如何从setInterval函数中访问变量"name" ?

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);
}
Run Code Online (Sandbox Code Playgroud)

jac*_*gel 12

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);
}
Run Code Online (Sandbox Code Playgroud)

这应该工作.匿名函数的"this"与myObject的"this"不同"this".