javascript new关键字对于javascript API功能是否可选? [英] Is javascript new keyword optional for javascript API feature?
问题描述
我很难理解为什么 new
关键字对JavaScript API对象/接口功能有利。
I having trouble to understand why the new
keyword is facultative for javascript API object/interface feature.
d = new String(); // javascript native object
d2 = String();
console.log(d);
console.log(d2);
控制台中的结果(这看起来很正常):
results in console (that seems pretty normal):
String {}
(an empty string)
但是:
b = new Blob(); // API object
b2 = Blob();
console.log(b);
console.log(b2);
结果:
Blob { size=0, constructor=function(), type="", more...}
Blob { size=0, constructor=function(), type="", more...}
而不是:
Blob { size=0, constructor=function(), type="", more...}
Blob() is undefined or (an empty blob)
一切正常,但我很好奇...
It all work just fine but I'm curious...
推荐答案
这是JS中的疣。有一些内部构造对象并返回它们的函数(不需要 new
),还有一些使用 new
做一堆魔术。
It's a wart in JS. There are functions that construct objects internally and return them (don't need new
), and "constructor functions" using new
that do a bunch of magic.
通常的建议是永远不要编写自己的类型来要求 new
,因为 new
要求功能的确做得不好,但如果您忽略它,就会有些微妙的事情(具体来说,它们将 this
绑定到全局对象而不是新对象,因此实例变量实际上是全局变量,并为实例成员分配全局变量)。如果必须使用它们,JavaScript:The Good Parts建议在名称中使用首字母大写来表示 require new和其他所有字母的首字母小写。
The usual recommendation is to never write your own types to require new
, because new
requiring functions do bad but subtle things if you omit it (specifically, they bind this
to the global object instead of a new object, so the instance variables are really the global variables, and assigning to instance members clobbers globals). If you must use them, JavaScript: The Good Parts recommends using initial capitals in the name to mean "requires new" and initial lowercase for everything else.
这篇关于javascript new关键字对于javascript API功能是否可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!