JavaScript SetInterval - 传递函数指针而不是String

时间:2009-09-18 20:32:07

标签: javascript

我有以下代码:

XService.start = function() {
  setInterval("XService.poll()", XService.pollInterval); }

XService.start = function() { setInterval("XService.poll()", XService.pollInterval); }

这很有效。但是,当我这样做时(将函数作为引用传递而不是使字符串eval'd)它停止工作:

XService.start = function() {
  setInterval(XService.poll, XService.pollInterval); }

为什么呢?我究竟做错了什么?我的代码中没有其他任何变化。我也在第二个版本尝试了XService.poll(),但也没有骰子。我读过的文档说出了()。

帮助?

编辑:XService.poll是一个函数; XService.pollInterval是一个数字。两者都被正确声明和分配。

Edit2:XService代码:

XService.start = function() { setInterval(XService.poll, XService.pollInterval); }

2 个答案:

答案 0 :(得分:1)

XService.poll是'function'和'XService.pollInterval'在特定时间的数字?

编辑:因为你刚刚发布了代码..

setInterval(

    function() {
        XService.poll();
    }, XService.pollInterval

);

答案 1 :(得分:0)

该功能的变化是什么。

当您调用第一个时,您的'this'语句绑定到XService对象。 当你调用第二个时,你的'this'语句被绑定到window对象。

例如,假设我们有像这样的民意调查的XService

function poll(){ alert(this); }

如果是第一个示例,它将提醒XService对象,但在第二个示例中,它将提醒窗口对象。

除了在mootools中我不知道语法,但在mootoos中你会调用

setInterval(XService.poll.bind(XService), 100)

它会正确调用方法

相关问题