Created
July 7, 2015 17:44
-
-
Save sstur/127f4623391a2040c228 to your computer and use it in GitHub Desktop.
Extend (subclass) native Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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