Array-like objects in JavaScript
Sep 29, 2013
bawigga
2 minute read

I learned something interesting in John Resig’s book Secrets of the JavaScript Ninja. How could you add Array like properties to your objects? At first thought, or at least my first thought, I would add an array to the object and then just use it internally as a collection, or maybe set the prototype to Array.prototype.

However, John points out a much simpler way. You can simply use  Array’s prototype methods on your object using call.

I decided to checkout the EcmaScript 5 standard (specifically Section 15.4.4 Properties of the Array Prototype Object) to find out more about these generic methods. Each property that could be used was said to be left “intentionally generic” and had a note similar to the following:

NOTE The concat function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the concat function can be applied successfully to a host object is implementation-dependent.

Here’s the full list of Array properties that are said to be generic:

  • Array.prototype.toString
  • Array.prototype.toLocaleString
  • Array.prototype.concat
  • Array.prototype.join
  • Array.prototype.pop
  • Array.prototype.push
  • Array.prototype.reverse
  • Array.prototype.shift
  • Array.prototype.slice
  • Array.prototype.sort
  • Array.prototype.splice
  • Array.prototype.unshift
  • Array.prototype.indexOf
  • Array.prototype.lastIndexOf
  • Array.prototype.every
  • Array.prototype.some
  • Array.prototype.forEach
  • Array.prototype.map
  • Array.prototype.filter
  • Array.prototype.reduce
  • Array.prototype.reduceRight

 

 



comments powered by Disqus