Javascript ES6,为什么我不能使用带有箭头功能的`new`? [英] Javascript ES6, why I can not use `new` with arrow function?
问题描述
据我所知,箭头函数类似于普通函数.我这样使用是没有问题的:
let X = () =>{};让 Y = 函数(){};X();Y();
但是,当我将它们与 new
let X = () =>{};让 Y = 函数(){};x = 新的 X();y = new Y();
未捕获的类型错误:X 不是构造函数
你能解释一下为什么吗?非常感谢.
您可能希望澄清您的问题.
问我做错了什么?
A. 您使用了带有箭头功能的 new
,这是不允许的.
问:我可以将箭头函数变成构造函数吗?
A. 仅将其包装在普通函数中,这很愚蠢.你不能把箭头函数本身变成构造函数.
问你能解释一下规范是如何禁止带有箭头函数的new
的吗?
A. 要成为构造函数,函数对象必须具有a [[Construct]]
内部方法.
使用 function
创建的函数关键字是构造函数,一些内置函数也是例如Date
.这些是您可以与 new
一起使用的函数.
其他函数对象没有[[Construct]]
内部方法.这些包括箭头函数.所以你不能将 new
与这些一起使用.这是有道理的,因为您 可以没有设置箭头函数的 this
值.
一些内置函数也不是构造函数.例如.你不能做 new parseInt()
.
Q. 你能解释一下禁止 new
背后的原因吗?规范中有箭头函数吗?
A. 使用常识,或搜索 es-discuss 档案.>
As far as I know, arrow function is similar to normal function. There is no problem when I use like this:
let X = () => {};
let Y = function() {};
X();
Y();
However, error occurred when I use them with new
let X = () => {};
let Y = function() {};
x = new X();
y = new Y();
Uncaught TypeError: X is not a constructor
Would you please explain me why? Many thanks.
You may wish to clarify your question.
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.
这篇关于Javascript ES6,为什么我不能使用带有箭头功能的`new`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!