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?
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:
this
as undefined
or global object in non strict mode): someMethod();
or var m = foo.methodTwo; m();
this
the object): foo.methodTwo()
this
the newly created object): new Foo()
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments