通过绑定this将回调从模块a传递到B,仍然具有B的作用域.使用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();
  }
};

当我在B.js中运行callback((时,this的作用域仍然是B?如果我把这个函数设为箭头函数,它也不起作用。

我创建了一个回购来证明这个问题:

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

希望有经验的人能够给出一个快速简单的解决方案。

您在ES6模块的顶层有一个静态声明的lambda,其中没有可供绑定的周围this。您从未显式地对函数执行bind,因此this的值应该是未定义的。看起来Babel在transpiling时没有提供强制undefined的绑定,最终得到了以前的this

对于带有箭头函数的对象文字,似乎存在一些混淆。箭头函数在声明时采用周围作用域的this值;对象文字不算作作用域,因此箭头函数不会绑定到对象。

如果您想绑定回调,您可以简单地将A模块更改为:

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

它应该开始工作了。正如您所看到的,箭头函数现在位于对象上调用的实际方法中。

您还有一个切向问题,import 'B'行旨在导入./B.js文件,但实际上是在查找node_modules/B/[entrypoint].js(即使涉及到webpack(。

最新更新