Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do ES6 arrow functions have their own arguments or not? [duplicate]

I don’t know whether arrow functions bind arguments to a lexical scope or not.

Take a look at this example (the same concept can be used for this):

var b = function() { return () => console.log(arguments); }; b(1,2,3)(4,5,6); // different result of chrome vs FF. 

When I run this on Chrome, I get [1,2,3], but on Firefox, I get [4,5,6]. What’s going on?

like image 373
Amin Roosta Avatar asked Oct 22 '15 19:10

Amin Roosta


People also ask

Do arrow functions have their own this?

Arrow functions treat this keyword differently. They don't define their own context since it doesn't have its own this context. They inherit that from the parent scope whenever you call this .

Do arrow functions define arguments?

The arrow function, on the opposite, doesn't define arguments (but you can easily access the arrow function arguments using a rest parameter ... args ). If the arrow function has one expression, then the expression is returned implicitly, even without using the return keyword.

Do arrow functions have their own binding to the this keyword?

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new. target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

Why arrow functions do not have their own this?

An arrow function doesn't have its own this value. Instead, it uses the this value of the enclosing lexical scope. An arrow function also doesn't have the arguments object. Avoid using the arrow function for event handlers, object methods, prototype methods, and functions that use the arguments object.


2 Answers

From the spec:

Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment.

Therefore, the correct answer would be [1,2,3]. Firefox has fixed the problem in version 43 (bug 889158).

like image 55
Oriol Avatar answered Sep 19 '22 14:09

Oriol


No, arrow functions don't have their own arguments, this, super, or new.target.

See the note at 14.2.16 Runtime Semantics: Evaluation:

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. Typically this will be the Function Environment of an immediately enclosing function.

like image 25
JMM Avatar answered Sep 16 '22 14:09

JMM