问题
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