JavaScript中奇怪的算术行为

Weird arithmetical behavior in JavaScript

本文关键字:JavaScript      更新时间:2023-09-26

我正在尝试用JavaScript编写自己的幻灯片。我已经拥有了一个在Opera,Safari和Chrome中工作的骨架:

var slideShow = (function() {
    var latestGames = document.getElementById('latestGames').getElementsByTagName('li');
    var displayedGame = 0;
    return {
        init: function() {
            latestGames[displayedGame].style.display = 'inline';
            setInterval(this.update, 3000);
        },
        update: function(gameToDisplay) {
            console.log("Displayed game: " + displayedGame);
            latestGames[displayedGame].style.display = 'none';
            gameToDisplay = gameToDisplay || (displayedGame === (latestGames.length - 1) ? 0 : ++displayedGame);
            console.log("Game to display: " + gameToDisplay);
            console.log('====================');
            latestGames[gameToDisplay].style.display = 'inline';
            displayedGame = (gameToDisplay == latestGames.length ? 0 : gameToDisplay);
        }
    }
})();

但是在 Firefox 中,当我记录 gameToDisplay 变量时,我只会得到随机数。我看不出错误在哪里。

事先谢谢。

使用以下代码:

var self = this; // preserve this to be used inside the callback
setInterval(function() { self.update(); }, 3000)

通常你所做的会起作用,但一些(基于 Gecko)浏览器将参数传递给计时器回调函数。

Firefox(pre-13)将参数传递给您的间隔处理程序。该参数给出了函数调用的"延迟";换句话说,超出应调用它的毫秒数。

请参阅此处的黄色警告:

注意:在壁虎13(火狐13.0/雷鸟13.0)之前,壁虎 向回调例程传递了一个额外的参数,指示 超时的"实际延迟"(以毫秒为单位)。这个非标准 不再提供参数。

setInterval每3秒调用一次this.update。 update将对该对象进行引用(this),但我不明白它将如何在gameToDisplay中传递。

要么删除gameToDisplay,因为它似乎是多余的,要么使其成为像displayGame这样的实例变量,并独立于update()进行设置。

在大多数情况下,它将为空,但 Firefox 显然会传递某种参数。