我想知道 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 对象的 proto 尤其有趣,因为它是 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] 但我猜答案就在那里。有人有任何想法吗?