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

Analysis of usage examples of extend in JQuery_jquery

May 16, 2016 pm 04:15 PM
extend jquery usage

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Detailed explanation and usage introduction of MySQL ISNULL function Detailed explanation and usage introduction of MySQL ISNULL function Mar 01, 2024 pm 05:24 PM

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Correct usage of POST request in PHP Correct usage of POST request in PHP Mar 27, 2024 pm 03:15 PM

The use of POST requests in PHP is a common operation in website development. Data can be sent to the server through POST requests, such as form data, user information, etc. Proper use of POST requests can ensure data security and accuracy. The following will introduce the correct usage of POST requests in PHP and provide specific code examples. 1. Basic principles of POST requests in PHP In PHP, the data submitted through the POST method can be obtained by using the $_POST global variable. The POST method converts the form number into

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles