[英]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.