javascript - 当作为参数传递时,对象方法回调会丢失其在事件处理程序中的绑定(bind),但在硬编码时不会

标签 javascript object callback this

我是 Javascript OOP 的新手,对绑定(bind)到事件处理程序中的回调有疑问。

我试图在我的构造函数中将事件处理程序应用于 DOM 元素。事件处理函数是对象的一个​​方法,我试图将回调函数(也是同一对象的一个​​方法)传递给该处理函数。

当我在处理程序中硬编码回调(使用 this.callbackMethod())时,它按预期运行:

class Foo {
  constructor (name){
    this.name = name
    this.bar();
  }
  callback(){
    console.log(this.name + 'bar callback this:') // 'foobar callback this:
    console.log(this) // Foo object with name 'foo'
  }
  bar(){
    document.querySelector('button').addEventListener('click', function(){
      console.log('bar click event this:')
      console.log(this)
      // this is the relevant line
      this.callback()
    }.bind(this));
  }
}

const foo = new Foo('foo');

但是,当我将该参数作为回调传递时,即使我在回调和处理程序上都使用 .bind(this),它也会失败:

class Foo {
  constructor (name){
    this.name = name
    this.bar(this.callback);
  }
  callback(){
    console.log(this.name + 'bar callback this:')// Uncaught TypeError: Cannot read property 'name' of undefined
    console.log(this)
  }
  bar(cb){
    document.querySelector('button').addEventListener('click', function(){
      console.log(cb)// logs function definition
      // this is the relevant line
      cb().bind(this); 
    }.bind(this));
  }
}

const foo = new Foo('foo');

代码笔示例:
硬编码回调:https://codepen.io/RandomNeuralFiring/pen/Pgrdey
参数回调:https://codepen.io/RandomNeuralFiring/pen/QPXVOR

我想要重新使用 bar() 和其他回调的选项,所以很想了解如何动态设置它的上下文。

附言我找不到适合对象绑定(bind)的标签 - 也许应该创建一个?

最佳答案

您正在绑定(bind)cb返回值 - 尝试先绑定(bind)函数然后调用它:

cb.bind(this)(); 

关于javascript - 当作为参数传递时,对象方法回调会丢失其在事件处理程序中的绑定(bind),但在硬编码时不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55945915/

相关文章:

javascript - 类型 T 的交​​错数组的类型定义及其数组原型(prototype)扩展

php - 构建个人 CMS - 类和库

java - C++ 二进制到 Java 得到 "java.lang.Error: Invalid memory access"

javascript - js如何获取动态下拉菜单的选定值

javascript - 将 materializecss 从 0.100.1 升级到 1.0.0 导致多个 javascript 错误

javascript - 难以理解和创建动态 JavaScript 对象

python - 在 python 中打印对象/实例名称

javascript - 如何在回调中访问正确的“this”?

javascript - 为什么 javascript 回调作为参数传递?

javascript - Jquery 返回 undefined 以引用 JSON