问题描述
所以,我正在尝试创建一个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);
});
问题在于kP
在document.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不适用于对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!