我想知道jQuery如何构建其类数组对象。我试图弄清楚的关键是它如何管理将其解释为数组并显示为数组。我知道这与length属性有关,但经过一番尝试,我仍然不太明白。我知道这与下面示例中的常规类数组对象没有技术上的优势。但我认为在用户测试和调试时,这是一个重要的语义元素。
一个常规的类数组对象。
一个常规的类数组对象。
function foo(){
// Array like objects have a length property and it's properties use integer
// based sequential key names, e.g. 0,1,2,3,4,5,6 just like an array.
this.length = 1;
this[0] = 'hello'
}
// Just to make sure add the length property to the prototype to match the Array
// prototype
foo.prototype.length = 0;
// Give the Array like object an Array method to test that it works
foo.prototype.push = Array.prototype.push
// Create an Array like object
var bar = new foo;
//test it
bar.push('world');
console.log(bar);
// outputs
{ 0: 'hello',
1: 'world',
length: 2,
__proto__: foo
}
而 jQuery 则会输出
var jQArray = $('div')
console.log(jQArray);
// outputs
[<div></div>,<div></div>,<div></div>,<div></div>]
如果你运行
console.dir(jQArray)
// Outputs
{ 0: HTMLDivElement,
1: HTMLDivElement,
2: HTMLDivElement,
3: HTMLDivElement,
4: HTMLDivElement,
context: HTMLDocument,
length: 5,
__proto__: Object[0]
}
jQuery对象的原型特别有趣,因为它是Object而不是预期的jQuery.fn.init,同时[0]指示着某些内容,因为这就是当你...时得到的内容。
console.dir([])
// outputs Array[0] as the object name or Array[x] x being the internal length of the
// Array
我不知道jQuery是如何将它的原型设置为Object[0]的,但我猜答案可能就在那里。有人有想法吗?
我不知道jQuery是如何将它的原型设置为Object[0]的,但我猜答案可能就在那里。有人有想法吗?