简体   繁体   中英

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

I'm new to Javascript OOP and have a question about binding to callbacks in event handlers.

I'm trying to apply an event handler to a DOM element in my constructor function. The event-handler function is a method of the object, and I'm attempting to pass a callback function (also a method of the same object) to that handler.

When I hard code the callback inside the handler (using this.callbackMethod()) it runs as expected:

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');

However, when I pass that parameter as a callback, even if I use .bind(this) on both the callback and the handler, it fails:

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');

Codepen examples:
Hard-coded callback: https://codepen.io/RandomNeuralFiring/pen/Pgrdey
Parameter callback: https://codepen.io/RandomNeuralFiring/pen/QPXVOR

I want the option of re-using bar() with other callbacks, so would love to understand how I can set its context dynamically.

PS I couldn't find a suitable tag for object-binding - perhaps one should be created?

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

cb.bind(this)(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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