我刚刚看到 John Resig 发表的一次谷歌技术演讲,他说 jQuery 作为数组运行。按照这个建议,我一直在玩子类数组,它工作得很好,但我一直在查看 jQuery 源代码,看不到他们使用了相同的方法
jQuery.prototype = new Array();
而且我什至无法通过调用/应用或在 window.$ 对象的原型(prototype)链中使用 native 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();
感谢您的回答
最佳答案
要“作为数组”工作(我们通常说的是“类数组”对象),您不必从 Array
继承,您只需
- 有一个名为
length
的相关属性 - 具有属性
"0"
、"1"
...length-1
(您可以跳过一些)
示例:
var a = {
length: 2,
"0": 'first',
"1": 'second'
}
var b = [].slice.call(a); // yes, Array functions work !
console.log(b); // logs ["first", "second"]
当然,您可以通过定义一个基于原型(prototype)的类和相关的原型(prototype)函数(就像 jQuery 所做的那样)来让 lib 用户更轻松地完成所有这些工作:
var A = function(){
this.length = 2;
this['0'] = 'first';
this['1'] = 'second';
}
A.prototype.slice = [].slice;
A.prototype.splice = [].splice;
var a = new A, b = a.slice();
console.log(a); // logs ["first", "second"] because of the splice function
console.log(Array.isArray(a));
console.log(b); // logs ["first", "second"] because it's really an array
console.log(Array.isArray(b)); // true
如果你想让你的对象被记录为数组,你需要有splice
函数。
关于javascript - jquery如何返回被选元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21706106/