簡體   English   中英

將回調從模塊A傳遞到B並以此綁定,仍然具有B的范圍。

[英]Passing a callback from module A to B with bound this, still has scope of B. Using babel

如果我將此“測試”功能從模塊A傳遞到模塊B,怎么辦:

 //A.js
import B from './B'
export default {
    self: this,
    test: ()=> {
        console.log(self === this)  // this should return true but doesn't because when B calls it, "this" is B
    },
    initA:function() {
        B.initB(this.test); // b is undefined here
    }
};

//B.js
export default {
  callback: null,
  initB: function (func) {
    callback = func;
  },
  startTest: function () {
    this.callback();
  }
};

該范圍this當我運行在B.js回調()仍然是B地? 如果我將此功能設為箭頭功能,也無法正常工作。

我創建了一個倉庫來演示這個問題:

https://github.com/es6Test/babel-test

希望有經驗的人能夠提供快速簡便的解決方案。

你必須在ES6模塊,那里是頂層靜態聲明的拉姆達周圍沒有this它綁定到。 您永遠不會顯式bind該函數,因此應該未定義this函數的值。 看起來Babel在轉譯時並未提供強制未定義的綁定,您最終獲得了this

帶有箭頭功能的對象文字似乎有些混亂。 箭頭函數在聲明時采用周圍范圍的this值; 對象文字算作一個范圍,所以箭頭功能將不結合到該對象。

如果要綁定回調,則只需將A模塊更改為:

export default {
  self: this,
  makeTest: function () {
    return () => {
      console.log(self === this)
    };
  },
  initA: ()=> {
    B.initB(this.makeTest());
  }
};

它應該開始工作。 如您所見,arrow函數現在位於在對象上調用的真實方法中。

您還會遇到一個切線問題,即import 'B'行是要導入./B.js文件,但實際上是在尋找node_modules/B/[entrypoint].js (即使涉及到webpack)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM