Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is .call supposed to work for ES6 Arrow Functions (according to the standards)?

I am using a cross-compiler (Babel, soon to be TypeScript) for ES6 and it currently does not support proper .call behavior for functions made with the => syntax; when I call them with .call, their this value is still the one they inherited from the parent scope when I first made them, instead of being the first argument I passed in with .call.

Is this their intentional behavior, as per the ES6 standards (which would be very disappointing)? Or is this just a limitation of the cross-compiler?

like image 973
Tahsis Claus Avatar asked Aug 07 '15 19:08

Tahsis Claus


People also ask

What is an ES6 arrow function?

Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions. For example, This function // function expression let x = function(x, y) { return x * y; }

What does => mean in ES6?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Why should arrow functions not be used in ES6?

An arrow function doesn't have its own bindings with this or super. An Arrow function should not be used as methods. An arrow function can not be used as constructors. An arrow function can not use yield within its body.

When should I use arrow functions in ES6?

When you should use them. Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself. Despite the fact that they are anonymous, I also like using them with methods such as map and reduce , because I think it makes my code more readable.


1 Answers

This is what the spec says:

An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment.

I.e. it's fixed to the context in where it was defined. You can't dynamically change it. Specifically on Function.prototype.call it says:

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

like image 61
Kit Sunde Avatar answered Oct 12 '22 23:10

Kit Sunde