如果我跑:
var dog = {
sound: "woof",
talk: function(){
console.log(this.sound)
}
}
document.addEventListener("click",dog.talk)
记录 undefined;只有当我将狗绑定到它的功能时 - document.addEventListener("click",dog.talk.bind(dog))
- 它是否有效。
为什么需要将狗绑定到它的方法?
这个函数是不是像狗一样被调用 - 只是将事件数据作为参数传递?
答案 0 :(得分:0)
我建议在this
上阅读以下内容。 http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
显然,this
仅在对象调用使用关键字this
的函数时定义。此时this
被定义为调用函数的对象。因此,在您的情况下,我认为this
将被绑定到文档对象。在你的函数中,this.sound
将引用document.sound,这是未定义的。
换句话说,即使你的狗对象内部看起来像{{1}}应该引用本地声音变量,它也不会在调用该函数的时候。
答案 1 :(得分:0)
行this
中的console.log(this.sound)
引用document
元素,而不是dog
对象。
var dog = {
sound: "woof",
talk: function(){
console.log(this)
console.log(this.sound)
}
};
document.addEventListener("click",dog.talk)
快照:
如果要在this
对象中使用dog
。您可以编辑活动:
var dog = {
sound: "woof",
talk: function(){
console.log(this)
console.log(this.sound)
}
};
document.onclick = function () {
dog.talk();
};