繁体   English   中英

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

[英]Object-method callback loses its binding in an event handler when passed as a parameter, but not when hard-coded

我是 Javascript OOP 的新手,有一个关于绑定到事件处理程序中的回调的问题。

我正在尝试将事件处理程序应用于构造函数中的 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() 与其他回调一起使用的选项,所以很想了解我如何动态设置其上下文。

PS 我找不到适合对象绑定的标签 - 也许应该创建一个?

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

cb.bind(this)(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM