Skip to content

Instantly share code, notes, and snippets.

@j201
Created June 25, 2014 03:22
Show Gist options
  • Save j201/e04fde312c3be19b4f41 to your computer and use it in GitHub Desktop.
Save j201/e04fde312c3be19b4f41 to your computer and use it in GitHub Desktop.
Subclassing arrays in JS with __proto__
subArrayProto = {
__proto__ : Array.prototype,
evenElements : function() {
return this.filter(function(el) {
return el % 2 === 0;
});
}
};
function makeSubArray() {
var inst = Array.apply(null, arguments);
inst.__proto__ = subArrayProto;
return inst;
}
var mySubArr = makeSubArray();
mySubArr[0] = 1;
mySubArr[1] = 8;
mySubArr[2] = 9;
mySubArr[3] = 4;
mySubArr.length; // 4
mySubArr.evenElements(); // 8,4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment