Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery extend()

Detailed explanation of jQuery extend()

小云云
小云云Original
2018-01-12 11:18:141269browse

This article mainly introduces you to the detailed explanation and simple examples of jQuery extend(). Friends who need it can refer to it. I hope it can help everyone.

jQuery extend() detailed explanation and simple examples

When you use jQuery, you will find that some functions in jQuery are used like this:


$.get(); 
$.post(); 
$.getJSON();

Some functions are used like this:


$('p').css(); 
$('ul').find('li');

Some functions are used like this:


$('li').each(callback); 
$.each(lis,callback);

There are two concepts involved here: tool methods and instance methods. Usually the tool methods we talk about refer to functions that can be called without instantiation, such as the first piece of code; instance methods are functions that can only be called after the object is instantiated, such as the second piece of code. Many methods in jQuery are both instance methods and tool methods, but the calling method is slightly different, such as the third piece of code. In order to explain the tool methods and instance methods in JavaScript more clearly, the following test is performed.


functionA(){ 
     
  } 
  A.prototype.fun_p=function(){console.log("prototpye");}; 
  A.fun_c=function(){console.log("constructor");}; 
  var a=new A(); 
  A.fun_p();//A.fun_p is not a function 
  A.fun_c();//constructor 
  a.fun_p();//prototpye 
  a.fun_c();//a.fun_c is not a function

It can be concluded from the above test that the instance method is defined in the prototype, and the tool method is added directly in the constructor; the instance method cannot Called by the constructor, similarly, tool methods cannot be called by instances.

Of course, instance methods can not only be defined in the prototype, there are the following three definition methods:


functionA(){ 
    this.fun_f=function(){ 
        console.log("Iam in the constructor"); 
    }; 
} 
A.prototype.fun_p=function(){ 
    console.log("Iam in the prototype"); 
}; 
var a=newA(); 
a.fun_f();//Iam in the constructor 
a.fun_i=function(){ 
    console.log("Iam in the instance"); 
}; 
a.fun_i();//Iam in the instance 
a.fun_p();//Iam in the prototype

These three ways The priority is: variables defined directly on the instance have a higher priority than those defined on "this", and variables defined on "this" are higher than variables defined by the prototype. That is, variables defined directly on the instance will overwrite variables defined on "this" and prototype, and variables defined on "this" will overwrite variables defined on prototype.

Let’s look at the source code of the extend() method in jQuery:


jQuery.extend = jQuery.fn.extend = function() { 
    var options,name, src, copy, copyIsArray, clone, 
        target= arguments[0] || {}, 
        i =1, 
        length= arguments.length, 
        deep= false; 
    // Handle adeep copy situation 
    if ( typeoftarget === "boolean" ) { 
        deep= target; 
        //Skip the boolean and the target 
        target= arguments[ i ] || {}; 
        i++; 
    } 
    // Handlecase when target is a string or something (possible in deep copy) 
    if ( typeoftarget !== "object" && !jQuery.isFunction(target) ) { 
        target= {}; 
    } 
    // ExtendjQuery itself if only one argument is passed 
    if ( i ===length ) { 
        target= this; 
        i--; 
    } 
    for ( ; i< length; i++ ) { 
        //Only deal with non-null/undefined values 
        if ((options = arguments[ i ]) != null ) { 
            //Extend the base object 
            for( name in options ) { 
                src= target[ name ]; 
                copy= options[ name ]; 
                //Prevent never-ending loop 
                if( target === copy ) { 
                   continue; 
                } 
                //Recurse if we&#39;re merging plain objects or arrays 
                if( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray= jQuery.isArray(copy)) ) ) { 
                   if( copyIsArray ) { 
                       copyIsArray= false; 
                       clone= src && jQuery.isArray(src) ? src : []; 
                   }else { 
                       clone= src && jQuery.isPlainObject(src) ? src : {}; 
                   } 
                   //Never move original objects, clone them 
                   target[name ] = jQuery.extend( deep, clone, copy ); 
                //Don&#39;t bring in undefined values 
                }else if ( copy !== undefined ) { 
                   target[name ] = copy; 
                } 
            } 
        } 
    } 
    // Returnthe modified object 
    return target; 
};

(1) First, jQuery and its prototype extend( ) method is implemented using the same function.

(2) When there is only one parameter in extend(), a plug-in is added to the jQuery object. What is extended on jQuery is called a tool method. What is extended in jQuery.fn (jQuery prototype) is an instance method. Even if you extend a function with the same name on jQuery and the prototype, using a jQuery object will call the tool method. Use jQuery() Instance methods are called.

(3) When there are multiple parameters in extend(), the subsequent parameters are extended to the first parameter.


var a={}; 
$.extend(a,{name:"hello"},{age:10}); 
console.log(a);//Object{name: "hello", age: 10}

(4) Shallow copy (default):


var a={}; 
varb={name:"hello"}; 
$.extend(a,b); 
console.log(a);//Object{name: "hello"} 
a.name="hi"; 
console.log(b);//Object{name: "hello"}

b is not affected by A is affected by a, but if an attribute in b is an object:


var a={}; 
varb={name:{age:10}}; 
$.extend(a,b); 
console.log(a.name);//Object{age: 10} 
a.name.age=20; 
console.log(b.name);//Object{age: 20}

Since the shallow copy cannot be completed, b.name will be affected by a. At this time we Often a deep copy is desired.

Deep copy:


var a={}; 
varb={name:{age:10}}; 
$.extend(true,a,b); 
console.log(a.name);//Object{age: 10} 
a.name.age=20; 
console.log(b.name);//Object{age: 10}

b.name is not affected by a.


 var a={name:{job:"Web Develop"}}; 
var b={name:{age:10}}; 
$.extend(true,a,b); 
console.log(a.name);//age: 10 job: "Web Develop"


  //b.name没有覆盖a.name.job。

Related recommendations:

About in jQuery Summary of the use of extend()

Comparison and use of clone() and extend() in jQuery

$.extend( in jQuery )Usage example_jquery

The above is the detailed content of Detailed explanation of jQuery extend(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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