Skip to content

Instantly share code, notes, and snippets.

@sstur
Created July 7, 2015 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sstur/127f4623391a2040c228 to your computer and use it in GitHub Desktop.
Save sstur/127f4623391a2040c228 to your computer and use it in GitHub Desktop.
Extend (subclass) native Array
function MyArray() {
var array = [];
if (arguments.length) {
array.push.apply(array, arguments);
}
// note: use `Object.setPrototypeOf` instead of __proto__ to be truly standards-compliant
array.__proto__ = MyArray.prototype;
return array;
}
// inherit properties and methods
MyArray.prototype.__proto__ = Array.prototype;
// custom methods
MyArray.prototype.last = function() {
var length = this.length;
return (length === 0) ? undefined : this[length - 1];
};
// static methods (emulate those of native Array)
MyArray.isArray = function(value) {
return (value instanceof MyArray);
};
MyArray.from = function() {
var array = Array.from.apply(Array, arguments);
array.__proto__ = MyArray.prototype;
return array;
};
MyArray.of = function() {
var array = Array.of.apply(Array, arguments);
array.__proto__ = MyArray.prototype;
return array;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment