在对象内使用绑定的Javascript,如何访问对象呢? [英] Javascript using bind within an object, how can I access object this?

查看:84
本文介绍了在对象内使用绑定的Javascript,如何访问对象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building an event manager for a little game that I am creating and have stumbled on a little problem (I don't know if it is a design pattern problem or if there is a solution to it)!

以下面为例;

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;

})();

即使我绑定了游戏,但如何在功能this中实际上是游戏,我该如何更改Events.mousedown标志?

How can I change the Events.mousedown flag even though I am binding game so that inside the function this is actually game?

谢谢

推荐答案

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

You will need to use a closure if you can't bind it. And I wouldn't bind the mousedown function to game either, as it's not a method on it. Simplicity rules:

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);
};

这篇关于在对象内使用绑定的Javascript,如何访问对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆