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?
Arrow functions cannot be used as constructors. They cannot be called with the new keyword.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With