Javascript在对象中使用bind,我该如何访问对象呢?

时间:2013-04-30 21:23:16

标签: javascript object this bind

我正在为一个我正在创建的小游戏构建一个事件管理器并且偶然发现了一个小问题(我不知道这是一个设计模式问题还是有解决方案)!

以下为例;

o.Events = (function() {

"use strict";

function mousedown() {

    // Set mousedown boolean

            // # How can I change o.Events.mousedown

    // For each layer
    this.layers.forEach(function(layer) {
        // Layer is listening
        if (layer.listening && layer.mouse.x && layer.mouse.y) {

            console.log("mousedown");
        }
    });
};

function init(game) {

    // Mousedown boolean
    this.mousedown = false;

    game.element.addEventListener("mousedown", mousedown.bind(game), false);
};

function Events(game) {

    // Initialize events
    init.call(this, game);
};

return Events;

})();

即使我绑定游戏,我怎样才能更改Events.mousedown标志,以便函数this内部实际上是游戏?

由于

1 个答案:

答案 0 :(得分:1)

如果无法绑定,则需要使用闭包。我也不会将mousedown函数绑定到game,因为它不是一个方法。简单规则:

o.Events = function Events(game) {
    "use strict";

    this.mousedown = false;
    var that = this;
    game.element.addEventListener("mousedown", function mousedown(e) {

        /* use
        e - the mouse event
        this - the DOM element ( === e.currentTarget)
        that - the Events instance
        game - the Game instance (or whatever was passed)
        */
        that.mousedown = true;

        // For each layer
        game.layers.forEach(function(layer) {
            // Layer is listening
            if (layer.listening && layer.mouse.x && layer.mouse.y)
                console.log("mousedown");
        });
    }, false);
};