public
Last active

Array subclass ES5

  • Download Gist
extend-array.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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-class-array.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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]
}}
})

I know that lot of time has passed since you make this gist, but this works nowadays... (chrome/firefox)

function SubArray() {
  this.push.apply(this, arguments);
}
SubArray.prototype = Object.create(Array.prototype, {
  constructor : { 
     value : SubArray
  },
  lastElement : {
    value : function() {
      return this[this.length - 1];
    }
  }
})

var sub = new SubArray(1, 2, 3);
sub instanceof SubArray; //true
sub instanceof Array; //true
sub.lastElement() //3

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.