Home > Web Front-end > JS Tutorial > Analysis of usage examples of extend in JQuery_jquery

Analysis of usage examples of extend in JQuery_jquery

WBOY
Release: 2016-05-16 16:15:15
Original
1018 people have browsed it

The example in this article describes the usage of extend in JQuery. Share it with everyone for your reference. The specific analysis is as follows:

The extend() function is one of the basic functions of jQuery, and its function is to extend existing objects. Extend is a commonly used method when we write plug-ins. This method has some overloaded prototypes. $.extend(prop) is used to extend the jQuery object and can be used to add functions to the jQuery namespace.

1. Source code of jQuery.extend function

jQuery.extend = jQuery.fn.extend = function() {
  var options, name, src, copy, copyIsArray, clone,
    target = arguments[0] || {},//参数目标对象
    i = 1,
    length = arguments.length,//参数长度
    deep = false;//是否为深度复制

  // Handle a deep copy situation
  //如果为深度复制,则目标对象和原对象游标值i,以及深度值都进行更新
  if ( typeof target === "boolean" ) {
    deep = target;
    target = arguments[1] || {};
    // skip the boolean and the target
    i = 2;
  }

  // Handle case when target is a string or something (possible in deep copy)
  //当目标对象的值类型错误,则重置为{}
  if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
    target = {};
  }

  // extend jQuery itself if only one argument is passed
  //当参数值长度为1的情况下,目标对象就为jQuery自身
  if ( length === i ) {
    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're merging plain objects or arrays
         //深度复制只有属性深度多于俩层的对象关系的结构的,如{a:{s:21,age:11}}或{a:['s'=>21,'age'=>11]}
        if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
          if ( copyIsArray ) {//如果是数组对象
            copyIsArray = false;
            clone = src && jQuery.isArray(src) &#63; src : [];

          } else {//普通对象
            clone = src && jQuery.isPlainObject(src) &#63; src : {};
          }

          // Never move original objects, clone them
          // 调用自身进行递归复制
          target[ name ] = jQuery.extend( deep, clone, copy );

        // Don't bring in undefined values
        } else if ( copy !== undefined ) {//非深度CP直接覆盖目标属性
          target[ name ] = copy;
        }
      }
    }
  }

  // Return the modified object
  return target;
};

Copy after login

2. Jquery’s extension method prototype is:

1. extend(dest,src1,src2,src3...);

Its meaning is to merge src1, src2, src3... into dest, and the return value is the merged dest. It can be seen that this method modifies the structure of dest after merging. If you want to get the merged result but don’t want to modify the structure of dest, you can use it as follows:

2. var newSrc=$.extend({},src1,src2,src3...)//That is, use "{}" as the dest parameter.

In this way, src1, src2, src3... can be merged, and then the merged result will be returned to newSrc.

Example below:

var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})
Copy after login

Then the merged result

result={name:"Jerry",age:21,sex:"Boy"}

Copy after login

That is to say, if the later parameter has the same name as the previous parameter, then the later parameter will overwrite the previous parameter value.

3. extend(boolean,dest,src1,src2,src3...)

The first parameter boolean represents whether to perform deep copy, and the other parameters are consistent with those introduced previously
For example:

var result=$.extend( true, {}, 
{ name: "John", location: {city: "Boston",county:"USA"} }, 
{ last: "Resig", location: {state: "MA",county:"China"} } );

Copy after login

We can see that the sub-object location: {city: "Boston"} is nested in src1, and the sub-object location: {state: "MA"} is also nested in src2. The first deep copy parameter is true, then The result after merging is:

result={name:"John",last:"Resig",location:{city:"Boston",state:"MA",county:"China"}}

Copy after login

That is to say, it will also merge the nested sub-objects in src, and if the first parameter boolean is false, let’s see what the result of the merger is, as follows:

var result=$.extend( false, {}, 
{ name: "John", location:{city: "Boston",county:"USA"} }, 
{ last: "Resig", location: {state: "MA",county:"China"} } );
Copy after login

Then the merged result is:

result={name:"John",last:"Resig",location:{state:"MA",county:"China"}}
Copy after login

2. When the extend method in Jquery omits the dest parameter

The dest parameter in the prototype of the extend method above can be omitted. If it is omitted, the method can only have one src parameter, and the src is merged into the object that calls the extend method, such as:

1.$.extend(src)

This method is to merge src into the global object of jquery, such as:

$.extend({
 hello:function(){alert('hello');}
});
Copy after login

is to merge the hello method into the global object of jquery.

2. $.fn.extend(src)

This method merges src into the jquery instance object, such as:

$.fn.extend({
 hello:function(){alert('hello');}
});
Copy after login

is to merge the hello method into the jquery instance object.

3. Here are some commonly used extension examples:

$.extend({net:{}});
Copy after login

This is to extend a net namespace in the jquery global object.

$.extend($.net,{
  hello:function(){alert('hello');}
})

Copy after login

This is to extend the hello method into the previously extended Jquery net namespace.

I hope this article will be helpful to everyone’s jQuery programming.

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