admin管理员组文章数量:1327488
I have a function inside a object that sets up a interval that calls another function but when ever that interval function is called it gives my a error saying Uncaught TypeError: Object [object Window] has no method
here is my code that I'm trying to understand.
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();
Thank you for your help!
I have a function inside a object that sets up a interval that calls another function but when ever that interval function is called it gives my a error saying Uncaught TypeError: Object [object Window] has no method
here is my code that I'm trying to understand.
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();
Thank you for your help!
Share Improve this question asked Sep 6, 2012 at 22:13 JustinJustin 1,2991 gold badge16 silver badges37 bronze badges 1- stackoverflow./questions/2749244/… – Michal Commented Sep 6, 2012 at 22:16
2 Answers
Reset to default 7When setInterval()
fires, the context is the global context (e.g. window), not your object. To call a method on your object and have the value of this
set appropriately in that method call, you need a separate function where you can call the method on your actual object like this:
this.start = function() {
//starts the interval function
var self = this;
this.timer = setInterval(function() {
self.loop();
}, 1000)
}
FYI, it is very mon when using an asynchronous functions like timers or ajax to save the context this
into a local variable so it can then be referenced from the embedded callback function even when this
is different in the callback function (as in your example). This is a mon design pattern.
I had a unique solution to this one. I got around it by making a function that calls my object method:
const globalSet = new globals();
function ut(){
globalSet.updateToasts();
}
setInterval(ut,15000);
It seems to have tricked JS into doing what I wanted.
本文标签:
版权声明:本文标题:Can't get setInterval function to call another function using this.function_name in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742201704a2432081.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论