Ale*_*llo 9 javascript oop javascript-events
我正在尝试为对象创建一个事件让它听它.请考虑以下示例:
var moon;
moon = document.createEvent("Event");
moon.initEvent("Event",true,true);
var Dog = function (name) {
this.name = name;
document.addEventListener("Event",this.bark,false);
};
dog.prototype.bark = function() {
console.log(this.name + ': Awooooooof Woof!');
};
var spot = new Dog("Spot");
var dot = new Dog("Dot");
//invoke
document.dispatchEvent(moon);
Run Code Online (Sandbox Code Playgroud)
我期待收到如下输出:
Spot: Awooooooof Woof!
Dot: Awooooooof Woof!
Run Code Online (Sandbox Code Playgroud)
但我得到的是:
undefined: Awooooooof Woof!
Run Code Online (Sandbox Code Playgroud)
我的例子出了什么问题?如何注册每个Dog实例的监听器?提前致谢!
Fab*_*ler 10
在这一行
document.addEventListener("Event",this.bark,false);
Run Code Online (Sandbox Code Playgroud)
你不绑定的范围this.bark来this.在JavaScript中,值this不依赖于函数的定义位置,而是取决于函数的调用位置.这意味着当您传递this.bark给addEventListener您时,将其与当前对象分离.
在像prototype.js和JQuery这样的框架中,有一些绑定的快捷方式this,使用vanilla JavaScript你可以这样做:
function bind(scope, fn) {
return function() {
return fn.apply(scope, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
document.addEventListener("Event",bind(this, this.bark),false);
Run Code Online (Sandbox Code Playgroud)