简体   繁体   English

javascript setInterval不适用于对象

[英]javascript setInterval not working for object

SO, I'm trying to create a javascript object, and use the setInterval method. 所以,我正在尝试创建一个javascript对象,并使用setInterval方法。

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. 另外,我正在使用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>

The solution provided by @Yacoby and @Nick, will work only if the play method doesn't use the this value inside itself, because the this value will point to the global object. @Yacoby和@Nick提供的解决方案仅在play方法本身不使用this值时才有效,因为this值将指向全局对象。

To handle this you need another approach, for example: 要处理这个问题,您需要另一种方法,例如:

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

See also: 也可以看看:

Call it like this: 像这样称呼它:

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

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). 问题是kPdocument.ready处理程序中并且在全局上下文中不可用(它仅在该闭包内可用)。 When you pass a string to setInterval() or setTimeout() it's executed in a global context. 将字符串传递给setInterval()setTimeout()它将在全局上下文中执行。

If you check your console, you'll see it erroring, saying kP is undefined, which in that context, is correct. 如果你检查你的控制台,你会发现它错误,说kP是未定义的,在这种情况下是正确的。 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);
});

You can see it working here 你可以看到它在这里工作

It works on every where like thymeleaf etc... 它适用于像thymeleaf等的每个地方......

function load() {
  alert("Hello World!");
}
setInterval(function () {load();}, 10000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM