问题描述
如果我将此“测试”功能从模块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地?
如果我将此功能设为箭头功能,也无法正常工作。
我创建了一个仓库来演示这个问题:
希望有经验的人能够提供快速简便的解决方案。
1楼
ssube
4
已采纳
2015-08-21 20:06:42
你必须在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)。