Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array subclass ES5
// No need to sub class Array if what you need is just an extended
// array. Example below illustrates the way to extend Array.
function SubArray() {
return Object.defineProperties(Array.prototype.slice.call(arguments), SubArrayDescriptor)
}
SubArray.prototype = Array.prototype
var SubArrayDescriptor =
{ constructor: { value: SubArray }
, last: { value: function last() {
return this[this.length - 1]
}}
}
// Sub classing array works as expected. Many people have false expectation that
// special behavior of number properties (sub[10]) is supposed to be inherited by a subclass.
function SubArray() {
var subArray = Object.create(SubArray.prototype)
Array.prototype.push.apply(subArray, arguments)
return subArray
}
SubArray.prototype = Object.create(Array.prototype,
{ constructor: { value: SubArray }
, last: { value: function last() {
return this[this.length - 1]
}}
})
@trusktr
Copy link

trusktr commented Apr 3, 2018

I'd like to note that the above examples re-write Array.from, which can break newer engines. For example, after the above patch, the following breaks in ES6:

Array.from( new Set([1,2,3,1,2,3]) )

The answers that use the patched Array.from are for ES5, and the newer example should be used for ES6.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment