Array subclass kind of hack
A simple way to extend Array by converting it in a function and propagating the new functions with a prototype (hacked) as function.
by microbians
JavaScript
console={}
console.log=function(t){
document.write(t+"<br/>")
}
listOfCustomArrays =[];
listOfCustomArrays.fn={};
Array_prototype=Array.prototype;
Array=function(){
// Add a new custom array to the list
listOfCustomArrays.push([]); // NEW ARRAY
listOfCustomArrays[listOfCustomArrays.length-1].index=listOfCustomArrays.length-1;
// The the current last
var arr=listOfCustomArrays[listOfCustomArrays.length-1];
for (j in listOfCustomArrays.fn) {
Object.defineProperty(arr, j, {
value: listOfCustomArrays.fn[j]
});
}
return arr
};
Array.extend=function(name,fnc) {
listOfCustomArrays.fn[name]=fnc;
for (i=0; i<listOfCustomArrays.length; i++) {
Object.defineProperty(listOfCustomArrays[i], name, {
value: listOfCustomArrays.fn[name]
});
}
}
Array.prototype=Array_prototype;
newCustomArray=new Array();
//Array.extend('f1', function(){console.log(1)} );
Array.prototype.f1=function(){console.log('f1:prototyped')};
Array.extend('f2', function(){console.log('f2:extended')} );
Array.extend('f3', function(){console.log('f3:extended')} );
newCustomArray2=new Array();
Array.extend('f4', function(){console.log('f4:extended')} );
console.log(typeof Array);
console.log(typeof []);
console.log("---------------------");
console.log(newCustomArray.f1);
console.log(newCustomArray.f2);
console.log(newCustomArray.f3);
console.log(newCustomArray.f4);
console.log("---------------------");
console.log(newCustomArray2.f1);
console.log(newCustomArray2.f2);
console.log(newCustomArray2.f3);
console.log(newCustomArray2.f4);
console.log("---------------------");
console.log([].f1);
console.log([].f2);
console.log([].f3);
console.log([].f4);
console.log("---------------------");
console.log(newCustomArray.forEach);
console.log(newCustomArray2.forEach);
console.log([].forEach);
console.log(Array.prototype.forEach);