DEV Community

loading...

Discussion on: Some lists are not like the others

Collapse
joelnet profile image
JavaScript Joel • Edited

You can take the fake array even further by forcing Array's prototype onto it:

const a = {
  '0': 'first',
  '1': 'second',
  '2': 'third',
  length: 3
};

a.__proto__ = Object.create(Array.prototype)

a.push('fourth')
//  \
//    Now we can use push!
//
//    We can also use map!
//  /
a.map(x => x.toUpperCase())
// [ 'FIRST', 'SECOND', 'THIRD', 'FOURTH' ]

btw... never write code like this ^

Cheers!

Collapse
krofdrakula profile image
Klemen Slavič Author

Correct, the power of prototypal inheritance allows you to quickly compose objects like that. 👌

The point of the exercise was to implement the methods directly, rather than just piggybacking off of the existing ones, though. It could have easily been an article about how to use prototypes to build your custom arrays, something that I might pick up a later date.

Forem Open with the Forem app