Javascript arrays created using Object.create - not real arrays?

It appears that the arrays created with Object.create are similar to arrays and quacks, such as arrays, but are still not real arrays. At least with v8 / node.js.

> a = [] [] > b = Object.create(Array.prototype) {} > a.constructor [Function: Array] > b.constructor [Function: Array] > a.__proto__ [] > b.__proto__ [] > a instanceof Array true > b instanceof Array true > Object.prototype.toString.call(a) '[object Array]' > Object.prototype.toString.call(b) '[object Object]' 

Can any Javascript guru explain why this is so, and how to make my newly created array indistinguishable from a real array?

My goal is to clone data structures, including arrays, which can have custom properties. I could, of course, manually bind the properties to the newly created array using Object.defineProperty , but is there a way to do this using Object.create ?

+8
source share
2 answers

The short answer is no. This article is explained in detail.

+5
source

No, you can’t. Object.create is all about prototypes, but both [] and Object.create(Array.prototype) inherit from the same prototype.

What you call the "desired behavior of Object.prototype.toString" is an internal [[Class]] object that cannot be set using Object.create . Creating "true arrays" (with the Array class and the behavior of a special array - indexed .length properties) is possible only using array literals or calling the Array constructor .

+3
source

All Articles