如何在Javascript原型中定义重复函数
How to define a repeating function in a Javascript prototype?
我试图定义一个带有重复函数的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
——在您的代码中,此计时器为repeater
和this
设置了新的作用域,不再指向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变量
相关文章:
- 用嵌套函数和默认函数定义函数
- 自定义函数中的光标位置
- Jquery未定义函数正在停止其他操作
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- javascript无法重新定义函数内部的全局对象
- 定义函数时,如何捕获外部变量的当前值
- 能够在定义函数表达式之前使用它
- Google Sheet自定义函数返回0
- Javascript-defineProperty和直接在对象上定义函数之间的区别
- 其中是自定义函数中的属性
- 创建自定义函数以在函数上运行完整的多选下拉列表
- Google Sheets自定义函数条件格式
- 为什么当我需要位于顶部的函数时,在脚本中的某些点上没有定义函数
- 使用变量的名称,然后为该变量定义函数
- dalek回调或自定义函数
- 如何在angular ui模态控制器中定义函数
- Uncaught ReferenceError:尝试在Android网络视图中访问时未定义函数
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 在构造函数中定义函数会比将其附加到原型消耗更多的内存
- 使用 Javascript 中的函数重新定义函数