Joelio
Joelio

Reputation: 4691

Array creation, why does this work?

I understand why :

 output = new Array();

and

 output = [];

but why does this work?

 output = Array();

Upvotes: 1

Views: 86

Answers (4)

Pointy
Pointy

Reputation: 413826

The Array() constructor is simply implemented such that calling it with new is 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:

function MyConstructor() {
  "use strict";
  var newObj = this || {};

  // ...

  return newObj;
}

When you invoke with new, the constructor will see that's it's got something bound to this. If you don't, then this will be undefined (because of "use strict"; you could alternatively check to see whether this is the global object, which you'd have to do for old IE).

The return value from a constructor is not the value of a new expression - that's always the newly-created object. When you call it without new, however, the return value will be used.

edit — RobG points out in a comment that for this to really work properly, the "synthetic" newObj that 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:

function MyConstructor() {
  "use strict";
  if (!this) return new MyConstructor();
  // ... or possibly using "apply" if you need parameters too
}

T.J. Crowder has written some awesome answers here on the subject of object/inheritance wrangling.

Upvotes: 3

mrk
mrk

Reputation: 5127

output = Array() works because Array is a function.

Run this cod3

<script>
var a = new Array();
var b = Array();
a[0] = 123;
b[0] = 32;
alert("a = " + a +"\nb = " +b +", " + Array);
</script>

This prints out:

a = 123
b = 32, function Array() {
    [native code]
}

So, since Array is a function, you can call Array(), which its implementation is to give you back a new Array()

Upvotes: 0

RobG
RobG

Reputation: 147453

The trivial answer is "because ECMA-262 says so". RTFM.

The first calls the Array function as a constructor, the second is an Array initialiser (aka Array literal).

The third is calling the Array function as a function and is equivalent to new Array() and [].

Upvotes: 0

jfriend00
jfriend00

Reputation: 707736

A function such as Array() can be written to detect whether it was called without the new operator and if new was omitted automatically create a new object and then return it.

Upvotes: 1

Related Questions