Is javascript new keyword optional for javascript API feature?

萝らか妹 提交于 2019-12-12 03:19:06

问题


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)

but:

b = new Blob(); // API object
b2 = Blob();
console.log(b);
console.log(b2);

results:

Blob { size=0, constructor=function(), type="", more...}
Blob { size=0, constructor=function(), type="", more...}

and not:

Blob { size=0, constructor=function(), type="", more...}
Blob() is undefined or (an empty blob)

It all work just fine but I'm curious...


回答1:


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.

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.



来源:https://stackoverflow.com/questions/32978852/is-javascript-new-keyword-optional-for-javascript-api-feature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!