当方法分配给一个variables时,ES6丢失范围

我发现和意外的行为。 任何人都可以解释为什么“这个”是当一个方法被引用到像下面的例子中的variables丢失?

class Foo { static bar() { return 'bar'; } baz() { return this.constructor.bar(); } } const foo = new Foo(); foo.baz(); // works fine const baz = foo.baz; baz(); // TypeError: Cannot read property 'constructor' of undefined 

要点: https : //gist.github.com/sznowicki/c076c52a0242c77a3044f4a79e9af4c3

代替:

 const baz = foo.baz; 

你可以做:

 const baz = foo.baz.bind(foo); 

这将确保foo在运行时在方法调用中绑定this

 baz(); 

有关更多信息,请参阅文档:

可以this看作是一个额外的parameter passing给方法,该方法携带一个方法被调用的对象。
所以: foo.baz()foo上被调用,而foo被这样传递。
但是baz()只是一个函数 (不是方法,因为它不记得以前定义的对象)。 在这里很难说这个价值是什么(也取决于'use strict'; )。

如何处理它

  1. 绑定它: const foo = bar.bind(instance)
  2. bar.apply(instance, ...)bar.call(instance, ...)调用它。
  3. 在函数中包装实例: const foo = function() { instance.bar() }const foo = () => instance.bar()
  4. 请记住,箭头函数与普通函数的处理方式不同 。