$('h1')如何作为jQuery中的数组记录到Web控制台? [英] How is $('h1') logging to the web console as an array in jQuery?
问题描述
如果在浏览器中执行 console.log($('some selector'))
,它会返回看起来像数组>
但请注意,它不是 instanceof Array
,但实际上是 jQuery
对象。
当你执行 console.dir($('h1'))
,它显示它实际上是jQuery对象。
问题是,它们如何使它看起来像是在Web控制台中的数组?我注意到在jQuery源这里他们添加参考到几个Array和Object方法,以及此处他们将 toArray
(和slice和其他)添加到 jQuery
对象。是web控制台以某种方式检查这些方法,如果它找到一个( toArray
, indexOf
, slice
等),它将它打印为一个数组?我想从任何自定义对象,如 Ember.ArrayProxy
得到这个行为。目前,当您记录 Ember.ArrayProxy
时,它显示>
任何想法?
div $ $ function SomeType(){
this.push(16);
}
SomeType.prototype = [];
SomeType.prototype.constructor = SomeType; //确保没有意外的结果
console.log(new SomeType()); //在控制台中显示为[16]
当然,所有jQuery对象都是 jQuery
函数/构造函数,所以这是jQuery的。作为一个奖励,由于继承,你得到 Array
中的所有方法,以及它的索引也!
If you do console.log($('some selector'))
in the browser, it returns what looks like an array (first line):
But notice that it's not an instanceof Array
, but it's actually the jQuery
object.
When you do console.dir($('h1'))
, it shows it's actually the jQuery object.
The question is, how are they making it look like it's an array in the web console? I noticed in the jQuery source here they add reference to a few Array and Object methods, and here they add toArray
(and slice and others) to the jQuery
object. Is the web console somehow checking for these methods and if it finds one (toArray
, indexOf
, slice
, etc.), it prints it as an Array? I would like to get this behavior out of any custom object, such as the Ember.ArrayProxy
. Currently when you log the Ember.ArrayProxy
it shows > Object
or whatever, but it would be nice to show it as an array.
Any ideas?
You make your object inherit Array
using the prototype, like so:
function SomeType() {
this.push(16);
}
SomeType.prototype = [];
SomeType.prototype.constructor = SomeType; // Make sure there are no unexpected results
console.log(new SomeType()); // Displays in console as [16]
And, of course, all jQuery objects are instances of the jQuery
function/constructor, so that's how jQuery does it. As a bonus, because of the inheritance, you get all the methods from Array
, and the indexing that comes with it too!
这篇关于$('h1')如何作为jQuery中的数组记录到Web控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!