Javascript在对象中使用绑定,我如何访问对象this

Javascript using bind within an object, how can I access object this?

本文关键字:对象 何访问 this 访问 Javascript 绑定      更新时间:2023-09-26

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

以下面为例;

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实际上是游戏?

谢谢

如果不能绑定闭包,则需要使用闭包。我也不会将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);
};