Home > Web Front-end > JS Tutorial > Detailed explanation of the difference between Jquery's $(selector).each() and $.each()

Detailed explanation of the difference between Jquery's $(selector).each() and $.each()

伊谢尔伦
Release: 2017-06-16 16:20:45
Original
1255 people have browsed it

We have all used the each function in Jqurey, and we all know that there are two ways to call each(), one is to call through $.each(), and the other is to call through $(selector).each() , so what’s the difference between them?

If you look at the Jquery source code, you will know that $.each() is the core implementation, $(selector).each() is the $.each() called, let’s first analyze $.each( ) source code (at the bottom):

The each (obj, callback, args) function receives 3 parameters: obj - the object or array to be traversed, callback - the callback function to be traversed and executed , args--the array specified by yourself (ignore it first).

The implementation of each method in jQuery uses the call method. The call method can set the context. First, in the following example, the effect of array each is the same. Why not call it directly?

You can change the pointer of this through call.

var testCall = function(obj, callback){
    callback.call(obj, 1);
}
Copy after login

testCall(["1. Change the pointer of this", "2. The function can be called internally through this"], function(index){ //Using the call method, you can directly access the call through this The object passed in as the first parameter.
alert(this[index]); //2. The function can be called through this });

Does not use the call method. this.

var test = function(obj, callback){
    callback(obj, 1);
}
Copy after login

test(["1. Change the pointer of this", "2. The function can be called through this inside the function"], function(index){ //Do not use call method, do not use this.
alert(this[index]); //undefined});

jQuery.each should be the this point modified by call;

$.each([1,2,3], function (index, item) {    console.log({index:index,value:item,_this:this});
});/*
  Object {index: 0, value: 1, _this: Number}
  Object {index: 1, value: 2, _this: Number}
  Object {index: 2, value: 3, _this: Number}
*/
Copy after login

I haven’t looked at the jQuery source code, use callback.call is a copycat and should be implemented in the same way.

var each = function(arr, callback){
  for( var index = 0 ; index < arr.length ; index++ ){
    callback.call(arr[index], index, arr[index]);
  }
}
each([1,2,3], function (index, item) {
    console.log({index:index,value:item,_this:this});
});/*
  Object {index: 0, value: 1, _this: Number}
  Object {index: 1, value: 2, _this: Number}
  Object {index: 2, value: 3, _this: Number}
*/
Copy after login

Note: this, if call is not used, this cannot be used in the callback function.

1. The case without args

Generally speaking, args are not commonly used, so we will not discuss the situation when if (args) is established first, that is, just look at the gray mark in the code part, this is also the core part of each() function

if(isArray) {
      for(; i < length; i++) {
        value = callback.call(obj[i], i, obj[i]);
        if(value === false) { break; }
      }
    }
Copy after login

If the object you want to traverse is an array type, enter this code block
 for loopTraverse Each element of the array , and then use the call method to execute obj[i].callback(i,obj[i]),
Therefore, when you write the callback function yourself, you should be aware that jquery will use arrays Each object in the callback method executes your callback function. The parameters passed are the index of the element in the array and the element. At the same time, this inside the callback method also points to the element;
The next line is to determine whether the callback function has returned a value. If the callback function returns false, break out of the array loop.

If the object you pass can also be traversed, the code is the same as the above array traversal

else {
      for(i in obj) {
          value = callback.call(obj[i], i, obj[i]);
          if(value === false) { break; }
        }
    }
Copy after login

If you pass the object, use for(x in y) to traverse Attributes of object ,
The principle is the same as above, except that it is replaced with the attribute x inside the object to execute the callback function, which is equivalent to obj.attr.callback(i,obj.attr);
Return If the function returns false, the loop operation will also end.

2. The situation with args

When calling each() with the third parameter, the following code block will be entered for analysis:  

if(isArray) {            
   for(; i < length; i++) {
     value = callback.apply(obj[i], args);                
     if(value === false) { break; }
            }
        } else {            
        for(i in obj) {
          value = callback.apply(obj[i], args);                
          if(value === false) { break; 
          }
        }
  }
Copy after login

In the same way, it will first determine whether the object you want to traverse is an array. If it is an array, traverse the element obj[i] of the array and execute obj[i].callback(args)
Note ! The parameter passed here is the args array you passed in. This is different from the args parameter without. That is to say, if you call the each function and pass in your own array parameter, the callbackParameters of the functionThe list is the args array you passed. Same as above for everything else.

$(selector).each(callback,args) function receives 2 parameters: callback--the callback function to be traversed and executed, args--the array specified by yourself. After understanding the $.each() function, $(selector).each is simple. Open the source code and find that the $.each() function is called inside $(selector).each. The source code is as follows:

each: function( callback, args ) {
      return jQuery.each( this, callback, args );
  },
Copy after login

You can see that when calling $.each(), the obj parameter is written as this, which is $(selector). This is the jquery selector returning a jqueryinternal object.  

Summary: The difference between $.each() and $(selector).each() is that the former can traverse all objects or arrays, while the latter is returned by the jquery selector jquery internal objects are traversed, the former is more powerful

The above is the detailed content of Detailed explanation of the difference between Jquery's $(selector).each() and $.each(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template