Javascript在对象中使用绑定,如何访问该对象?
我正在为我正在创建的一个小游戏创建一个事件管理器,但遇到了一个小问题(我不知道这是设计模式问题还是有解决方案) 以下面为例Javascript在对象中使用绑定,如何访问该对象?,javascript,object,this,bind,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.f
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;
})();
即使我正在绑定游戏,如何更改事件.mousedown
标志,以便在函数中此
实际上是游戏
谢谢如果无法绑定,则需要使用闭包。我也不会将
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);
};
只要引用它就可以了
o.Events.mousedown=…
只要看一点客户端代码就可以了。也就是说,使用您创建的这个事件对象的代码。在构造函数或mousedown(e)中使用“That=this”。。。e、 事件的目标“使用它=此;外面的换成里面的…谢谢这更有意义