[英]Javascript using bind within an object, how can I access object this?
我正在为正在创建的小游戏构建事件管理器,但偶然发现了一个小问题(我不知道这是设计模式问题还是解决方案)!
以下面为例;
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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.