How to mimic arrays in javascript?

Viewed 528

I'd like to understand how Arrays are specified and built.

I'm mixing arrays with extra methods and trying to pass in Array.isArray(). I can pass instanceof and Poly-filled isArray

var protoOfArray = Object.getPrototypeOf([])

var tools4Arrays = Object.defineProperty(
  Object.create(protoOfArray),
  'sum', {
    'value': function sum() {
      return this.reduce((a, b) => a + b, 0)
    }
  }
)
tools4Arrays[Symbol.toStringTag] = 'Array'

var fakeArray = Object.defineProperty(
  Object.create(
    tools4Arrays
  ),
  'length', {
    'value': 0,
    'writable': true
  }
)

console.log(`fakeArray instanceof Array: ${fakeArray instanceof Array}`)
console.log(`polyfill.isArray(fakeArray): ${Object.prototype.toString.call(fakeArray) === '[object Array]'}`)
console.log(`Array.isArray(fakeArray): ${Array.isArray(fakeArray)}`)

If I use: fakeArray = Object.setPrototypeOf([], tools4Arrays) the last log is true too.

What else separates arrays of objects? Can I mock it?

2 Answers

In order to mimic an Array you'd have to pass the internals of isArray which has the following checks (defined here):

  1. If Type(arg) is not Object, return false.
  2. If the value of the [[Class]] internal property of arg is "Array", then return true.
  3. Return false.

The Type here appears to be the same as instanceof, which you've been able to pass just fine. However, the second step points at some internal [[Class]] property, which I'm not sure we have write access to.

Related