I just saw a google tech talk presented by John Resig where he said jQuery works like an array. After this tip, I was playing with a subclass array, and it works fine, but I was looking at the jQuery source and can't see that they used the same method
jQuery.prototype = new Array();
And I do not see it even when using my own Array.prototype.methods with a call / application or in the prototype chain in a window. $ object, so I wonder how the jQuery object returns an array of selected elements.
I tried using a regular object, but when returning an array, it stops the possibility of a chain of commands
If you can take some methods from Array.prototype, what is needed to return the array?
This is what I played with.
;(function(window, document, undefined){
function MyLib(){};
function Core(){};
function Methods(){};
function myLib(selector){
return new MyLib().construct(selector);
}
myLib.extend = function(module, name, fn){
if(typeof fn === 'function'){
if(!MyLib.prototype[module][name]){
MyLib.prototype[module][name] = fn;
}
} else if(typeof fn === 'object'){
for(var key in fn){
if(!MyLib.prototype[module][key]){
MyLib.prototype[module][key] = fn[key];
}
}
} else {
throw new Error("invalid type, function or objects are required");
}
}
MyLib.prototype = new Array();
MyLib.prototype.core = new Core();
MyLib.prototype.methods = new Methods();
MyLib.prototype.construct = function(selector){
var elems = document.getElementsByTagName(selector);
Array.prototype.push.apply(this, Array.prototype.slice.call(elems, 0, elems.length));
return this;
};
myLib.core = MyLib.prototype.core;
myLib.methods = MyLib.prototype.methods;
window.$ = myLib;
window.$$ = MyLib;
})(window, document);
$.extend('methods', 'test', function(){alert('method successfully added')});
$.methods.test();
$('tagName').test();
thanks for any answers