Skip to content

Instantly share code, notes, and snippets.

@grimen
Forked from xk/SubArray.js
Last active December 17, 2015 10:29
Show Gist options
  • Save grimen/5595639 to your computer and use it in GitHub Desktop.
Save grimen/5595639 to your computer and use it in GitHub Desktop.
// 20111028 jorge@jorgechamorro.com
// How to subclass Array
// In reply to https://gist.github.com/1100841/9c959db9314338a09c0f288c2c0ca5553816e400
function subArray () {
var nu = Array.prototype.slice.apply(arguments); // @grimen: Fixed to support `new Array(666)` (=> `[666]` instead of Array of size 666)
nu.__proto__= subArray.prototype;
return nu;
}
subArray.prototype= {
__proto__: Array.prototype,
custom: function () { return "custom" }
}
/*
o= new subArray(1,2,3)
[ 1, 2, 3 ]
o instanceof Array
true
o instanceof subArray
true
o.custom()
'custom'
o.length
3
o.length=5, o
[ 1, 2, 3, , ]
o.length=2, o
[ 1, 2 ]
o.push(3), o
[ 1, 2, 3 ]
...etc
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment