How does .call work with ES6 Arrow (according to standards)?

I use the cross-compiler (Babel, which will soon be TypeScript) for ES6, and currently it does not support the correct .call behavior for functions created with => syntax; when I call them .call , their this value still remains the one they inherited from the parent area when I first made them, instead of being the first argument I passed with .call .

Is this their intentional behavior according to ES6 standards (which would be very disappointing)? Or is it just a cross compiler limitation?

+4
source share
2 answers

Here is what the spec says:

The ArrowFunction function does not define local bindings for arguments, super, this, or new.target. Any reference to the arguments, super, this or new.target inside ArrowFunction should allow binding in a lexical environment.

those. it is fixed in the context where it was defined. You cannot dynamically change it. In particular, Function.prototype.call says:

If func is an arrow function or a related function, then thisArg will be ignored by the [[Call]] function in step 5.

+4
source

If you use a function of type methodical below, it will create a method in which this is passed as the first argument to the callback. Thus, you have all the advantages of the thick arrow syntax (implicit return, this not lost on subsequent function calls), but can still use it as a method. Of course, there is also a short method syntax that basically creates the traditional es5 style function (slightly different since it cannot be called with the new one).

 const methodical = func => function(...args) { return func(this, ...args) } const add = methodical( (instance, name, value) => (instance[name] = value, instance) ) const a = { add } a.add('first', 1.23).add('second', 2.74) add.call(a,'third', 3.11) console.log(JSON.stringify(a, null, 2)) 

using es2015 shorthand methods instead

 const b = { add(name,value) { this[name] = value return this } } b.add('first',1).add('second',2) console.log(JSON.stringify(b)) 
0
source

All Articles