Skip to content

Instantly share code, notes, and snippets.

@DC3
Forked from Gozala/extend-array.js
Created September 18, 2017 03:36
Show Gist options
  • Save DC3/9af0eea99fda1b7e303c289e1bb43951 to your computer and use it in GitHub Desktop.
Save DC3/9af0eea99fda1b7e303c289e1bb43951 to your computer and use it in GitHub Desktop.
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]
}}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment