簡體   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