为什么我必须将此对象绑定到自己的方法?

时间:2016-10-15 06:53:43

标签: javascript oop object scope this

如果我跑:

var dog = {
    sound: "woof",
    talk: function(){
        console.log(this.sound)
    }
}
document.addEventListener("click",dog.talk)
记录

undefined;只有当我将狗绑定到它的功能时 - document.addEventListener("click",dog.talk.bind(dog)) - 它是否有效。

为什么需要将狗绑定到它的方法?

这个函数是不是像狗一样被调用 - 只是将事件数据作为参数传递?

2 个答案:

答案 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)

快照:

1

如果要在this对象中使用dog。您可以编辑活动:

var dog = {
    sound: "woof",
    talk: function(){
        console.log(this)
     	console.log(this.sound)
    }
};

document.onclick = function () {
	dog.talk();
};