1

这是我认为我需要描述这个问题的所有内容的代码片段。我正在尝试在激活 mousedown 时执行连续操作,但出现错误:

Uncaught ReferenceError: e is not defined (匿名函数)

我很确定这个错误源于 beginAction 函数,我在引号中有 findClick(e) ,不知何故我认为 e 在这里没有正确传递。

function Cell(row, column) {
    this.row = row;
    this.column = column;
    }

function foo(bar) {
    //do stuff here
    gCanvas.addEventListener("mousedown", beginAction, false);
    document.addEventListener("mouseup", endAction, false);
    }

function beginAction(e) {
    findClick(e);
    var findClick_timeout = setInterval("findClick(e)", 50);
    }

function endAction(e) {
    if (typeof(findClick_timeout) != "undefined"){ clearTimeout(findClick_timeout);}
    }

function getCursorPosition(e) {
    //finds the cell position here... works
    var cell = new Cell(Math.floor(y/cellSize), Math.floor(x/cellSize));
    return cell;
    }

function findClick(e) { 
    var cell = getCursorPosition(e);
    //do stuff with the cell!!!!!!
    }
4

1 回答 1

2

计时器字符串被转换为全局范围内的函数。这就是为什么你不应该使用它们:

var findClick_timeout = setInterval(function() { findClick(e); }, 50);

这样,那个小匿名函数将可以从创建它的“beginAction”函数访问“e”。但是,当您只传递一个字符串时,运行时会在全局范围内评估它,并且没有“e”在那里。

在较新的浏览器中,您可以使用一个名为“bind”的函数:

var findClick_timeout = setInterval(findClick.bind(this, e), 50);

它只是一个工具,本质上是做匿名函数所做的事情。

于 2012-07-21T20:43:56.993 回答