Created
November 7, 2010 17:10
-
-
Save Gozala/666251 to your computer and use it in GitHub Desktop.
Array subclass ES5
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
// 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] | |
}} | |
} |
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
// 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
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:The answers that use the patched
Array.from
are for ES5, and the newer example should be used for ES6.