我刚刚看了John Resig的谷歌技术演讲,他说jQuery作为一个数组运作。听从这个建议后,我尝试使用一个子类化的数组,并且效果很棒,但是我查看了jQuery源代码,并��有看到他们使用相同的方法:
我尝试使用普通对象,但如果返回一个数组,就会停止链接命令的能力。如果有可能从`Array.prototype`中获取一些方法,则什么是返回一个数组必要的?
这是我正在尝试的内容。
感谢任何回答。
jQuery.prototype = new Array();
甚至在`window.$`对象的原型链中,也没有调用`Array.prototype.methods`的原生方法,所以我想知道jQuery对象如何返回所选元素的数组。我尝试使用普通对象,但如果返回一个数组,就会停止链接命令的能力。如果有可能从`Array.prototype`中获取一些方法,则什么是返回一个数组必要的?
这是我正在尝试的内容。
;(function(window, document, undefined){
function MyLib(){};
// prototype constructor functions
function Core(){};
function Methods(){};
// create new instance of the MyLib object and call the construct method
function myLib(selector){
return new MyLib().construct(selector);
}
// allow adding new methods to the prototype from the window.
// eg $.extend('module', 'name', 'function')
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;
};
// access to prototype objects with $.core && $.methods
myLib.core = MyLib.prototype.core;
myLib.methods = MyLib.prototype.methods;
// give the window access to the constructor function
window.$ = myLib;
// give the window access to the prototype object for debugging
window.$$ = MyLib;
})(window, document);
// this adds a new method to the methods object within the prototype
$.extend('methods', 'test', function(){alert('method successfully added')});
// the added method can be accessed with
$.methods.test();
// or
$('tagName').test();
感谢任何回答。