Stack: A native Array wrapper that works
Date : 2008 05 21 Category : Tech & DevelopmentAndrea Giammarchi has created a native array wrapper that works across browsers. He is excited:
I do not know how many times, during this years, JavaScript Ninjas have tried to subclass the native Array to create libraries over its powerful methods without losing performance. I have finally discovered the way to remove the locked length from Internet Explorer 8, and to solve problems with every other browser.
He ended up with the Stack class:
PLAIN TEXT JAVASCRIPT:/** * Choose a name for subclassed Array */ Stack = (function(){ // (C) Andrea Giammarchi - Mit Style License /** * Your personal Array constructor */ function Stack(length){ if(arguments.length === 1 && typeof length === "number") this.length = -1 <length && length === length <<1>> 1 ? length : this.push(length); else if(arguments.length) this.push.apply(this, arguments); }; // Solution 1: // Declaration of generic function // with an array as prototype function Array(){}; Array.prototype = []; // Solution 2: // use the prototype chain to inherit // Array constructor and its native prototype Stack.prototype = new Array; // Solution 3: // overwrite inherited length with zero value Stack.prototype.length = 0; // Solution 4: // redeclare toString method in this way // to let JScript core feel better Stack.prototype.toString = function(){ return this.slice(0).toString(); }; /** * Return and assign subclassed Array */ Stack.prototype.constructor = Stack; return Stack; })();