1

好的,我在 JavaScript 中有一个问题,我创建了一个函数构造函数并添加了一个属性和方法,当一个方法被调用以使用对象环境方法作为基本示例时,它具有一个基本示例,因为我的构造函数太复杂了。

function Construct(){
this.alert = 'test1';
this.replace = '';
this.interval;
this.run = function(){
console.log(this);//echo the constructor
this.interval = setInterval(function(){
console.log(this);//echo the window object
alert(this.alert);
this.replace = '';
}
};
}

如果您已阅读代码,则此操作失败,您必须了解原因。

我如何将构造函数对象(this)传递给设置间隔函数?

我曾尝试使用外部函数并将其作为参数传递,但它失败了,因为替换仍然是原样并且它只是一次符文,为什么?

请帮忙。

谢谢你。

4

1 回答 1

2

创建一个局部self变量,并将其设置为this,以便您可以在嵌套函数中使用它:

function Construct () {

    this.alert = 'test1';
    this.replace = '';
    this.interval;

    this.run = function () {

        var self = this;

        this.interval = setInterval(function () {
            self.replace = '';
        }, 500);
    };
}
于 2013-09-16T02:38:07.293 回答