如何在Javascript原型中定义重复函数

How to define a repeating function in a Javascript prototype?

本文关键字:定义 函数 原型 Javascript      更新时间:2023-09-26

我试图定义一个带有重复函数的Javascript,但我无法使其工作:

var Repeater = function() {
    this.init.apply(this, arguments);
};
Repeater.prototype = {
    run: 0, // how many runs
    interval: 5, // seconds
    init: function() {
        this.repeat();
    },
    repeat: function() {
        console.log(++this.run);
        setTimeout(this.repeat, this.interval * 1000);
    }
};
var repeater = new Repeater();

应该如何做到这一点?

试试这个代码:

var Repeater = function() {
    this.run = 0;  // how many runs
    this.interval = 5; // seconds
    this.init.apply(this, arguments);
};
Repeater.prototype.init = function() {
    this.repeat();
}
Repeater.prototype.repeat = function() {
    var _this = this;
    console.log(++this.run);
    setTimeout(function () { _this.repeat() }, this.interval * 1000);
};
var repeater = new Repeater();

我已经将run和interval移到了构造函数中,因为如果您将其添加到原型中,那么它将分布在所有实例中。

您的问题在于seTimeout——在您的代码中,此计时器为repeaterthis设置了新的作用域,不再指向Repeater实例,而是指向Timeout实例。您需要缓存this(我称之为_this),并将其调用到传递给setTimeout的新函数中。

这样尝试:

var Repeater = function() {
    this.init.apply(this, arguments);
};
Repeater.prototype = {
    run: 0, // how many runs
    interval: 5, // seconds
    init: function() {
        this.repeat();
    },
    repeat: function() {
        console.log(++this.run);
        var that = this;
        setTimeout(function() {that.repeat()}, this.interval * 1000);
    }
};
var repeater = new Repeater();

你可以在这个问题中阅读更多关于CCD_;这个";关键词工作?

更改repeat函数以在setTimeout调用中使用闭包,如下所示:

repeat: function() {
var ctx = this;
    console.log(++this.run);
    setTimeout(function(){ctx.repeat()}, this.interval * 1000);
}

在这类场景中,您需要显式地设置上下文-这就是的ctx变量