2

I believe (may be I wrong) method definition at ECMA6 uses arrow functions (internally) and "this" (context) must be kept. But

class Foo {
    methodOne() {
        console.log("MethodOne is called")
    }

    methodTwo() {
        console.log("MethodTwo is called");
        this.methodOne();
    }
}

var foo = new Foo();

var executing = function (someMethod) {someMethod()};

executing(foo.methodTwo)

It raises error "Uncaught TypeError: Cannot read property 'methodOne' of undefined(…)"

So, either I understood specification incorrect or browsers (Chrome, FF) and nodejs does not support this yet?

vmusulainen
  • 328
  • 3
  • 7

2 Answers2

3

Classes in ES6 are just syntactic sugar over prototypal inheritance. This way the method declarations in the class are attached to the prototype object.

1) The problem in the example is in the way the function is invoked. To keep the context this, you still need to invoke it as a method on an object:

var foo = new Foo();

var executing = function (someMethod, context) {someMethod.apply(context)};

executing(foo.methodTwo, context);

2) But if you invoke it as a regular function, then you'll have this as undefined in strict mode:

 methodTwo() {
        console.log("MethodTwo is called");
        this.methodOne(); // <---- `this` is `undefined`
 }

this in a function call is determined by the way it is invoked:

  1. as regular function (makes this as undefined or global object in non strict mode): someMethod(); or var m = foo.methodTwo; m();
  2. as a method on an object (makes this the object): foo.methodTwo()
  3. as constructor (makes this the newly created object): new Foo()
  4. indirect invocation (using apply(newContext) and call(newContext)): someMethod.apply(context).

Notice that bound() method can modify the context before invocation. It will cancel any later context modifications on invocation for cases 1, 2 and 4. For constructor invocation the bound context is ignored and still used the newly created object.

Check this nice post about the function context and invocation in JavaScript.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
1

So, either I understood specification incorrect or browsers (Chrome, FF) and nodejs does not support this yet?

Whichever part of the spec you read, you misunderstood it. Methods and arrow functions are two different things, and even if methods had arrow function semantics, you wouldn't get the behavior you expected (since arrow functions resolve this lexically).

No, methods work like normal function declararions/expressions wrt to this.

See also How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143