【问题标题】:Why must I bind this object to its own method?为什么我必须将此对象绑定到它自己的方法?
【发布时间】:2017-02-24 15:26:12
【问题描述】:

如果我跑:

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

未定义已记录;只有当我将狗绑定到它的功能时 - document.addEventListener("click",dog.talk.bind(dog)) - 它才有效。

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

函数没有像正常一样在狗身上被调用——只有事件数据作为参数传递?

【问题讨论】:

  • 当对象调用talk方法时,this将引用调用者对象,因此this将引用调用者对象而不是dog对象。
  • 你在全局文档上设置了点击事件监听器。这意味着每次点击(无论在哪里),您都会触发您提供的dog.talk 函数。
  • 你想完成什么?获取用户点击的 HTML 元素?

标签: javascript oop object scope this


【解决方案1】:

我建议在this 上阅读以下内容。 http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

显然,this 仅在对象调用使用关键字 this 的函数时定义。而此时this 被定义为调用该函数的对象。因此,在您的情况下,this 将被绑定到文档对象。在您的函数中,this 将引用未定义的 document.sound。

换句话说,即使在您的 dog 对象内部,this.sound 应该引用本地声音变量,但在调用该函数时并没有。

【讨论】:

    【解决方案2】:

    console.log(this.sound) 中的this 指的是document 元素,而不是dog 对象。

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

    快照:

    如果你想在dog 对象中使用this。您可以编辑事件:

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

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多