JavaScript addEventListener添加对当前对象的引用

JavaScript addEventListener add a reference to the current object

本文关键字:对象 引用 addEventListener 添加 JavaScript      更新时间:2023-09-26

我简化了代码来说明这个问题。

function SnakeGame ()
{
    this.snakeDirection         = 'right';
    this.Init = function ()
    {
        window.addEventListener('keydown', this.keyboardInput, false);
    }
    this.keyboardInput = function (event, SnakeGameObject)
    {
        console.log(SnakeGameObject); //Error since I can't pass this variable...
        console.log(event.keyCode); //Works
    }
}

在this.keyboardInput函数中,我尝试更改变量this.snakeDirection;问题是我无法获得SnakeGame对象的引用。在键盘输入功能中,这指的是窗口。我理解为什么它指的是窗口,但我想不出解决方案。。。

完整的代码可以在这里看到:http://eriknijland.nl/stackoverflow/snake_event_listener/

虽然Mythril的答案是正确的,但我建议您不要将方法用作事件回调。因为:a)它们是公开的,所以一旦你的代码变得更大,就很容易被否决;b)它们是可公开访问的:

var snakeInstance = new SnakeGame();
var otherObject = new SomethingElse();
snakeInstance.keyboardInput.apply(otherObject,[]);//invokes method, uses self, though self !== otherObject, but snakeInstance.

所以我用一个闭包:

function SnakeGame()
{
    this.snakeDirection = 'right';
    var keyBoardInput = (function(that)
    {
        return function(e)
        {
            console.log(that);
            console.log(e.keyCode);
        }
    })(this);
    this.Init = function()
    {
        document.body.addEventListener('keydown',keyboardInput,false);
    }
}

还要记住,您的代码并不完全兼容X浏览器(addEventListener&&attachEvent?)

如果目标是ES5(你应该是),你应该写:

window.addEventListener('keydown', this.keyboardInput.bind(this), false);

这将确保总是以CCD_ 1作为其上下文来调用回调。

试试这个:

function SnakeGame ()
{
    var self = this;
    this.snakeDirection         = 'right';
    this.Init = function ()
    {
        window.addEventListener('keydown', this.keyboardInput, false);
    }
    this.keyboardInput = function (event)
    {
        console.log(self); 
        console.log(event.keyCode); //Works
    }
}