将回调从模块 A 传递到 B 并绑定 this,仍然具有 B 的范围。使用 babel

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

如果我将这个 'test' 函数从模块 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 可以绑定。您永远不会显式 binding 函数,因此 this 的值应该是未定义的。看起来 Babel 在转译时没有提供强制未定义的绑定,你最终得到了之前的 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)。