Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ES6, why I can not use `new` with arrow function? [duplicate]

As far as I know, the arrow function is similar to a normal function. There aren’t any problem when I use it like this:

let X = () => {};
let Y = function() {};
X();
Y();

However, the error occurred when I used them with new:

let X = () => {};
let Y = function() {};
x = new X();
y = new Y();

Uncaught TypeError: X is not a constructor

Why is that?

like image 429
Ricky Avatar asked Jun 02 '16 09:06

Ricky


People also ask

Can we use new keyword in arrow function?

Arrow functions cannot be used as constructors. They cannot be called with the new keyword.

Why does this function not work in arrow?

An arrow function saves the binding of this in the closure that's created when the function is created. So it doesn't set this to the context of the call to the function. In your case, this was bound to window when you created the object, so this.

Which keyword is not used when using arrow function?

target keyword. Arrow functions aren't suitable for call , apply and bind methods, which generally rely on establishing a scope. Arrow functions cannot be used as constructors. Arrow functions cannot use yield , within its body.

What does () => mean in JavaScript?

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.


1 Answers

Q. What did I do wrong?

A. You used new with an arrow function, and that's not allowed.

Q. Can I turn an arrow function into a constructor?

A. Only by wrapping it in a normal function, which would be silly. You can't turn an arrow function itself into a constructor.

Q. Can you explain how the specification disallows new with arrow functions?

A. To be a constructor, a function object must have a [[Construct]] internal method.

Functions created with the function keyword are constructors, as are some built-in functions such as Date. These are the functions you can use with new.

Other function objects do not have a [[Construct]] internal method. These include arrow functions. So you can't use new with these. This makes sense since you can't set the this value of an arrow function.

Some built-in functions are also not constructors. E.g. you can't do new parseInt().

Q. Can you explain the rationale behind disallowing new with arrow functions in the specification?

A. Use common sense, or search the es-discuss archives.

like image 62
1983 Avatar answered Nov 02 '22 00:11

1983