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);
@felipenmoura
Copy link

Really cool, dude.
Useful, once you want, sometimes to change the Array prototype but you know it might "damage" other library, for example!

As we were talking...Google Chrome exposes us to a very tricky situation!
These console.log calls will end up in a bunch of really weird values!

This is tricky because it is not a fault in your code, but in the console itself! The console must be always referencing the same log...when you change the value of a property, it simply changes the wrong place into the console, causing some time to identify the problem!
It looks to be fine in Firefox and Opera's consoles!

Nice code, by the way :)

@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