jQuery each() - 它是如何在内部工作的? [英] jQuery each() - How does it work really internally?
问题描述
我已就此咨询了jQuery的来源,但我必须承认这可能超出了我的理解 - 或者我在寻找错误的地方。
https://github.com/jquery/jquery/blob /master/src/core.js
I've consulted the jQuery source on this, but I must admit it's probably beyond my understanding - or I'm looking in the wrong place. https://github.com/jquery/jquery/blob/master/src/core.js
在第222行附近有一个看起来递归的函数,然后在第566行附近再次声明了另一个函数.extend()命名空间。
Around line 222 there is a function that looks recursive, and then again around line 566 there is another one declared in .extend() namespace.
我只是好奇 - 这究竟是如何工作的?例如,当我打电话时:
I'm just curious - how exactly does this work? For example, when I call:
$('.item').each(function(){
// Do Something
});
如何知道循环访问DOM元素数组,何时停止,它是如何应用的功能?它不能只做
How does it know to cycle through the array of DOM elements, when to stop, how does it apply the function? It cant just do
$('.item').doThis()
因为doThis()可能不是该对象的成员。
because doThis() might not be a member of that object.
请赐教: )谢谢。
推荐答案
不,它不是递归的。 第222行上的函数是关于jQuery原型的函数( $。fn
),而它调用的函数是 jQuery.each
- 一个静态属性,在< a href =https://github.com/jquery/jquery/blob/master/src/core.js#L566 =nofollow>第566行。请注意 如何扩展
有效:如果没有给出要扩展的对象,它使用这个
。它在代码的不同部分都应用于 jQuery
和 jQuery.fn
。
No, it is not recursive. The function on line 222 is the one on jQuery's prototype ($.fn
), while the function it calls is jQuery.each
- a static property which is defined in line 566. Notice how extend
works: If no object to extend is given, it uses this
. It is both applied on jQuery
and jQuery.fn
in different sections of the code.
那么这究竟是如何工作的?
so how exactly does this work?
$ obj.each(callback)
正在调用 $。fn.each
方法,该方法应用 $。每个
关于jQuery实例(DOM包装器)本身:第223行。
$obj.each(callback)
is calling the $.fn.each
method, which applies $.each
on the jQuery instance (the DOM wrapper) itself: line 223.
现在,在 $。每个
中,有四种情况:或者没有提供 args
数组,以及类似数组的结构或其他对象。你没有传递额外的args,jQuery实例有一个 length
属性,并且在数字索引中有DOM元素,所以第596行将被执行。所以你的电话相当于
Now, in $.each
, there are four cases: With or without supplied args
array, and on an array-like structure or on other objects. You didn't pass additional args, and jQuery instances have a length
property and have the DOM elements in numeric indices, so the loop in line 596 will be executed. So your call is equivalent to
for (var i=0, len=$obj.length; i<len; i++)
if ( callback.call($obj[i], i, $obj[i]) === false ) break;
这篇关于jQuery each() - 它是如何在内部工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!