Created
June 16, 2014 07:51
-
-
Save Williammer/82338cf7b7fea0b85196 to your computer and use it in GitHub Desktop.
jsMethod.borrowArray.js - borrow native methods of Array, ensure compatibility by not subclass Array.
This file contains hidden or 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() {} | |
| //MyArray.prototype = new Array(); //subclass Array, which is not compatible across all browsers. | |
| MyArray.prototype.length = 0; | |
| (function () { | |
| var methods = ['push', 'pop', 'shift', 'unshift', | |
| 'slice', 'splice', 'join']; | |
| for (var i = 0; i < methods.length; i++)(function (name) { | |
| MyArray.prototype[name] = function () { | |
| return Array.prototype[name].apply(this, arguments); | |
| }; | |
| })(methods[i]); | |
| })(); | |
| var mine = new MyArray(); | |
| mine.push(1, 2, 3); | |
| assert(mine.length == 3, | |
| "All the items are on our sub-classed array."); | |
| assert(!(mine instanceof Array), | |
| "We aren't subclassing Array, though."); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment