Javascript ES6,为什么我不能使用带箭头功能的`new`? [英] Javascript ES6, why I can not use `new` with arrow function?
问题描述
据我所知,箭头功能与普通功能类似。我这样使用时没有问题:
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();
然而,当我使用 new
let X = () => {};
let Y = function() {};
x = new X();
y = new Y();
未捕获的TypeError:X不是构造函数
会不会请你解释一下为什么?非常感谢。
Would you please explain me why? Many thanks.
推荐答案
您可能希望澄清您的问题。
You may wish to clarify your question.
问。我做错了什么?
Q. What did I do wrong?
A。你用过<带箭头功能的code> new ,这是不允许的。
A. You used new
with an arrow function, and that's not allowed.
Q。我可以将箭头函数转换为构造函数吗?
Q. Can I turn an arrow function into a constructor?
A。仅将其包装在正常函数中,这将是愚蠢。
您无法将箭头函数本身转换为构造函数。
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。您能解释一下规范吗?使用箭头功能禁止 new
?
Q. Can you explain how the specification disallows new
with arrow functions?
A。成为构造函数,一个函数对象必须有
a [[Construct]]
内部方法。
A. To be a constructor, a function object must have
a [[Construct]]
internal method.
使用函数创建的函数
关键字是构造函数,一些内置函数
,例如 Date
。这些是您可以使用的函数 new
。
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
.
其他函数对象没有 [[Construct]]
内部方法。这些包括箭头功能。所以你不能用
使用 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.
在函数中也不是构造函数。例如。你
不能新的parseInt()
。
Some built-in functions are also not constructors. E.g. you
can't do new parseInt()
.
Q. 你能解释一下在规范中使用箭头函数禁用 new
背后的理由吗?
Q. Can you explain the rationale behind disallowing new
with arrow functions in the specification?
A。使用常识,或搜索 es-discuss archives 。
A. Use common sense, or search the es-discuss archives.
这篇关于Javascript ES6,为什么我不能使用带箭头功能的`new`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!