Tuesday 16 May 2017

ES6 lost scope when method is assigned to a variable

I found and unexpected behavior. Can anyone explain why "this" is lost when a method is referenced to a variable like in an example below?

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

Gist: https://gist.github.com/sznowicki/c076c52a0242c77a3044f4a79e9af4c3



via sznowicki

No comments:

Post a Comment