search
HomeWeb Front-endJS TutorialHow to use extend in jQuery

How to use extend in jQuery

Apr 02, 2018 pm 04:12 PM
extendjqueryInstructions


This article shares with you a detailed explanation of how to use extend in jQuery. The content is quite good. I hope it can help friends in need

Method introduction

In the jQuery API manual, the extend method is mounted on two different objects: jQuery and jQuery.fn, but the internal code implementation of jQuery is the same, but the functions are different. Are not the same.

Let’s take a look at the official explanation first:

  • jQuery.extend Merge the contents of two or more objects together into the first object. Merge two or more objects into the first object;

  • jQuery.fn.extend Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. Mount the object to jQuery's prototype to extend a new jQuery Instance method.

Although there is no official mention of the extension method function of jQuery.extend, it also has the function of extending jQuery Class method .

Merge objects

First of all, let me introduce the usage of extend function in Merge objects.

jQuery.extend(target [, object1] [, objectN])

Merge object1 ... objectN to the target object. If there is only one parameter, the target object will be merged into the jQuery object.

var obj1 = {
    name: 'Tom',
    age: 21
}

var obj2 = {
    name: 'Jerry',
    sex: 'boy'
}

$.extend(obj1, obj2); // {name: "Jerry", age: 21, sex: "boy"}

obj1 // {name: "Jerry", age: 21, sex: "boy"}
obj2 // {name: "Jerry", sex: "boy"}

上述代码展示的是将 obj2 对象合并到 obj1 对象中,这种方法会 改变 obj1 对象的结构。如果你 不想改变 合并目标对象的结构,你可以这么做。

var obj1 = {
    name: 'Tom',
    age: 21
}

var obj2 = {
    name: 'Jerry',
    sex: 'boy'
}

$.extend({}, obj1, obj2); // { name: "Jerry", age: 21, sex: "boy" }

obj1 // { name: "Tom", age: 21 }
obj2 // { name: "Jerry", sex: "boy" }

深浅拷贝

jQuery.extend([deep], target, object1 [, objectN])

和上面的讲述的不同的是,该方法多了一个类型为 boolean 的 [deep] 传参,当其为 true 时,将 object1 , objectN 深度复制 后合并到 target 中。

首先,我们理解一下什么叫做 深度复制 。看看其和 浅度复制 有什么区别。

var obj1 = {
    name: "John",
    location: {
        city: "Boston",
        county: "USA"
    }
}

var obj2 = {
    last: "Resig",
    location: {
        state: "MA",
        county: "China"
    }
}

$.extend(false, {}, obj1, obj2); // { name: "John", last: "Resig", location: { state: "MA", county: "China" }}

$.extend(true, {}, obj1, obj2); // { name: "John", last: "Resig", location: { city: "Boston", state: "MA", county: "China" }}

由此可见,执行 深度复制 会递归遍历每个对象中含有复杂对象(如:数组、函数、json对象等)的属性值进行复制,而且 浅度复制便不会这么做。

方法扩展

上述的 extend 方法中的 target 参数是可以省略的。如果省略了,则该方法就只能传入一个 object 参数,该方法功能是将该 object 合并到调用 extend 方法的对象中。

我们通常会使用这种方式来对 jQuer进行一些方法上的扩展。

引子

jQurey 提供了两种方法扩张方式,分别为jQuery.fn.extend(object)jQuery.extend(object).

想要搞清楚两种扩展方式之间的区别的话,先要了解什么是jQuery.fn.

本猿参考了 jQuery 的源码,发现其中玄机:

jQuery.fn = jQuery.prototype = {   
    init: function(selector, context) {
        // ...
    };
}

jQuery.fn = jQuery.prototype这句代码明确指出jQuery.fn指代的就是 jQuery 的原型

其次,我们要引入两个概念 类方法 和 实例方法 。

  • 类方法 是直接可以使用类引用,不需要实例化就可以使用的方法。一般在项目中 类方法 都是被设置为工具类使用;

  • 实例方法 必须先创建实例,然后才能通过实例调用该 实例方法 。

jQuery可以看做是这个封装得非常好的类,而我们可以使用jQuery选择器来创建 jQuery 的实例。比如:使 id 选择器$('#btn')来创建一个实例。

区别

jQuery.extend(object)相当于对 类方法 的扩展。

jQuery.extend({
    /* 返回两个元素中较小的值 */
    min: function(a, b) {
        return a < b ? a : b;
    },
    /* 返回两个元素中较大的值 */
    max: function(a, b) {
        return a > b ? a : b;
    }
});

jQuery.min(2, 3); // 2 
jQuery.max(4, 5); // 5

jQuery.fn.extend(object)是对jQuery.prototype上的扩展。

jQuery.fn.extend = jQuery.prototype.extend

这种方式相当对 实例方法 的扩展。

举个栗子:
开发一个简单的小功能,使用该方法可以使选定元素内的文字变红。

$.fn.extend({
    setRed: function() {
        $(this).css("color", "red");
    }
});

$(&#39;.tip&#39;).setRed();

$(".tip")创建了一个jQuery实例,通过它可以调用成员方法setRed.

上述代码可以实现预想的扩展,但最好返回this 以满足 jQuery 链式操作 的需要。

改良之后,代码如下:

$.fn.extend({
    red: function() {
        return $(this).css("color", "red");
    }
});

The above is the detailed content of How to use extend in jQuery. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.