可以't获取setInterval函数以使用javascript中的this.function_name调用另一
Can't get setInterval function to call another function using this.function_name in javascript
我在一个对象中有一个函数,它设置了一个调用另一个函数的间隔,但当调用该间隔函数时,它会给我一个错误,说Uncaught TypeError:object[object Window]没有方法
这是我正在努力理解的代码。
function test2() {
this.timer;
this.say = function(){
console.log("hi");
}
this.start = function() {
//starts the interval function
this.timer = setInterval(this.loop, 1000)
}
this.loop = function() {
//runs every 1 second
this.say(); //gives error -- Uncaught TypeError: Object [object Window] has no method 'say'
}
}
var test = new test2();
test.start();
谢谢你的帮助!
setInterval()
触发时,上下文是全局上下文(例如窗口),而不是对象。要在对象上调用一个方法,并在该方法调用中适当设置this
的值,您需要一个单独的函数,可以在其中调用实际对象上的方法,如下所示:
this.start = function() {
//starts the interval function
var self = this;
this.timer = setInterval(function() {
self.loop();
}, 1000)
}
仅供参考,当使用定时器或ajax等异步函数将上下文this
保存到本地变量中时,这是非常常见的,这样即使this
在回调函数中不同(如您的示例),也可以从嵌入的回调函数中引用它。这是一种常见的设计模式。
我有一个独特的解决方案。我通过创建一个函数来绕过它,该函数调用我的对象方法:
const globalSet = new globals();
function ut(){
globalSet.updateToasts();
}
setInterval(ut,15000);
它似乎欺骗了JS去做我想做的事。
相关文章:
- this内部的值返回this.each(function(){})
- This.props.dispatch not a function - React-Redux
- jQuery $(this) inside function
- 重复“;function(){}.调用(this)"在Uglified JS中
- Javascript get "this" class with onClick function
- 用(function(){…}).call(this)包装文件,而用简单的()包装调用
- Function.length和this.length不一样.为什么
- jQuery: addClass and click function for this class
- 函数(){}.bind(this) 和 angular.bind(this, function() {}) 之间的区别
- Advantage of (function() {/*...*/}).call(this);
- this.function 和 this.function() 之间的区别
- 为什么使用 (function(){}).call(this);.
- this.function不是函数错误,但函数存在
- TypeError:调用Function.protype.method()时,this.prototype未定义
- undefined is not a function when evaluating 'this.batman
- Javascript setTimeout function with 'this'
- this.text Function
- 为什么object.function.this在使用function.call时没有定义
- JavaScript: change function(this) to function(this.id)
- AJAX function(this)