javascript setInterval不适用于对象 [英] javascript setInterval not working for object

查看:68
本文介绍了javascript setInterval不适用于对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在尝试创建一个javascript对象,并使用setInterval方法.

SO, I'm trying to create a javascript object, and use the setInterval method.

这似乎不起作用.如果删除引号,则该方法运行一次.有什么想法吗?另外,我正在使用Jquery.

This doesn't seem to be working. If I remove the quotes, then the method runs once. Any ideas why? Also, I'm using Jquery.

<script>
$(function(){
   var kP = new Kompost();
   setInterval('kP.play()', kP.interval);
});

var Kompost = function()
{
   this.interval = 5000;
   var kompost = this;

   this.play = function()
   {
      alert("hello");
   }
}
</script>

推荐答案

像这样调用它:

$(function(){
   var kP = new Kompost();
   setInterval(kP.play, kP.interval);
});

问题在于kPdocument.ready处理程序内部,而在全局上下文中可用(仅在该闭包内部可用).当您将字符串传递给setInterval()setTimeout()时,它是在全局上下文中执行的.

The problem is that kP is inside that document.ready handler and not available in the global context (it's only available inside that closure). When you pass a string to setInterval() or setTimeout() it's executed in a global context.

如果检查控制台,则会看到错误消息,表示未定义kP,在这种情况下,这是正确的.总体来说,它应该像这样:

If you check your console, you'll see it erroring, saying kP is undefined, which in that context, is correct. Overall it should look like this:

var Kompost = function()
{
   this.interval = 5000;
   var kompost = this;
   this.play = function() {
     alert("hello");
   };
};

$(function(){
   var kP = new Kompost();
   setInterval(kP.play, kP.interval);
});

您可以在这里看到它的工作

这篇关于javascript setInterval不适用于对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆