Created
June 25, 2014 03:22
-
-
Save j201/e04fde312c3be19b4f41 to your computer and use it in GitHub Desktop.
Subclassing arrays in JS with __proto__
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
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