Skip to content

Instantly share code, notes, and snippets.

@hns
Created November 5, 2010 10:24
Show Gist options
  • Save hns/663932 to your computer and use it in GitHub Desktop.
Save hns/663932 to your computer and use it in GitHub Desktop.
subclassing arrays in ES5 - working or not?
// The following attempts to extend arrays *kind* of work with ES5
// except you get Objects masquerading as Arrays. Seems like an
// oversight in ES5 Object.create() (15.2.3.5) to me.
// simple approach where you don't need a constructor:
arr1 = Object.create(Array.prototype, {x: {value: 1}});
// use a proper constructor
function SubArray() {}
SubArray.prototype = new Array();
arr2 = Object.create(SubArray.prototype, {x: {value: 1}});
// what does work is using the non-standard __proto__ property on an existing array:
function SubArray() {}
SubArray.prototype = Object.create(Array.prototype, {x: {value: 1}})
// SubArray.prototype is not a real array, but we don't care -
// it's enough for instanceof Array to work
arr = [];
arr.__proto__ = SubArray.prototype
// voila, arr is now a proper Array subclass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment