I understand why :
output = new Array();
and
output = [];
but why does this work?
output = Array();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
Array()constructor is simply implemented such that calling it withnewis unnecessary. It’s part of its semantic definition.Built-in constructors like
Array()are (probably) not written in JavaScript, but you can get the same effect in your own code:When you invoke with
new, the constructor will see that’s it’s got something bound tothis. If you don’t, thenthiswill be undefined (because of “use strict”; you could alternatively check to see whetherthisis the global object, which you’d have to do for old IE).The return value from a constructor is not the value of a
newexpression – that’s always the newly-created object. When you call it withoutnew, however, the return value will be used.edit — RobG points out in a comment that for this to really work properly, the “synthetic”
newObjthat the function creates needs to be explicitly set up so that it’s got the proper prototype etc. That’s kind-of tricky; it might be simplest for the code to simply do this:T.J. Crowder has written some awesome answers here on the subject of object/inheritance wrangling.