简体   繁体   中英

Javascript Constructor of new Object([]) / new Object(new Array())

Regarding : new Object(new Array())

there's a quite rather fundamental question that me myself really could not come up with an answer to, which i am seeking advice for:
When instantiating an object in js using the following method:
var obj = new Object();
It's obvious: ,

,

when doing something slightly different such as instantiating an object of type Array:

var obj = new Object([]);

becomes
obj.constructor === Array

What exactly is happening here?
I fully get why in the first example obj.constructor === Object
but why is the constructor of obj Array when the Array was created via new Object?

Wouldn't the constructor of obj on first roll have to be Object.constructor?

As var obj = new Object([]); is the same as var obj = new Object(new Array());

  • Would this mean the constructor returned by a new Object that was itself creating a new Object of another type, would always the the latest/newest assigned in that "chain"?
  • Or does object simply inherit the constructor from it's first parameter (of specific type)?


Cheerio

Lets have a look at the specification:

15.2.2.1 new Object ( [ value ] )
When the Object constructor is called with no arguments or with one argument value, the following steps are taken:

  1. If value is supplied, then
    a. If Type( value ) is Object, then
    i. If the value is a native ECMAScript object, do not create a new object but simply return value .

That means, if you pass an object to Object , it simply returns the very same value. So var obj = new Object([]); is really the same as var obj = []; , and we can easily test that:

> var arr = []; // or var arr = new Array();
> var obj = new Object(arr);
> arr === obj;
true

If you pass an argument that is not an object, it will be converted to an object, eg

> typeof new Object("string")
'object'

If you don't supply any argument, it simply returns a new object:

> new Object()
Object {}

Also note that as per specification, Object(...) behaves exactly like new Object(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM