Skip to content

Instantly share code, notes, and snippets.

@leobalter
Created July 15, 2011 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leobalter/1084009 to your computer and use it in GitHub Desktop.
Save leobalter/1084009 to your computer and use it in GitHub Desktop.
Array Extender. Creates an Array subclass. Doing so you won't override or mess with Array's own prototype
var ArrayExtender = function (a) {
var counter = 0;
for (var i in a) {
if (a.hasOwnProperty(i)) {
this[i] = a[i];
++counter;
}
}
this.length = counter;
};
var ArrProto = Array.prototype;
var ArrExtProto = {};
for (var i in ArrProto) {
if (ArrProto.hasOwnProperty(i)) {
ArrExtProto[i] = ArrProto[i];
}
}
ArrayExtender.prototype = ArrExtProto;
ArrayExtender.prototype.count = function () {
for(var i in this) {
if (this.hasOwnProperty(i)) {
console.log("Element "+i+" is "+this[i]);
}
}
};
console.log("2 lines returning an expression and a undefined value");
console.log(ArrayExtender.prototype.count);
console.log(Array.prototype.count);
console.log("now this should return more lines");
var thisWouldWin = new ArrayExtender([123, 234]);
console.log(thisWouldWin);
thisWouldWin.count();
console.log(thisWouldWin.length);
thisWouldWin.push(345);
console.log(thisWouldWin.length);
@leobalter
Copy link
Author

this is happening in Opera's dragonfly too...

if someone else didn't get the trick check the console at line 39's return: [123, 234, 345], but 345 is pushed after this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment