将此对象在构造函数中传递给setInterval

时间:2013-09-16 02:35:47

标签: javascript object

好的我在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)传递给set interval函数?

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

请帮助。

谢谢。

1 个答案:

答案 0 :(得分: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);
    };
}