search
HomeWeb Front-endJS TutorialDetailed explanation and examples of jQuery.extend() implementation_javascript skills

Copy code The code is as follows:


<script><BR>obj1 = { a : 'a', b : 'b' };<BR>obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' }; <P>$.extend(true, obj1, obj2); <P>alert(obj1.x.xxx); // Get "xxx" <P>obj2.x.xxx = 'zzz';<BR>alert(obj2.x.xxx); // Get "zzz"<BR>alert(obj1.x.xxx); // Must bring "xxx" <BR></script>

$.extend(true, obj1, obj2) means to extend object obj1 with the attributes in obj2. The first parameter is set to true to mean deep copy.
Although obj1 originally did not have the "x" attribute, after expansion, obj1 not only has the "x" attribute, but also the modification of the "x" attribute in obj2 will not affect the "x" attribute in obj1 Value, this is the so-called "deep copy".

Implementation of shallow copy

If you only need to implement shallow copy, you can use something like the following:

Copy code The code is as follows:

$ = {
extend : function(target, options) {
for (name in options) {
target[name] = options[name];
}
return target;
}
};

That is, simply copy the attributes in options to the target. We can still test with similar code, but get different results (assuming our js is named "jquery-extend.js"):
Copy code The code is as follows:


<script><BR>obj1 = { a : 'a', b : 'b' };<BR>obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' };<BR>$.extend(obj1, obj2);<BR>alert(obj1.x.xxx); // Get "xxx"<BR>obj2.x.xxx = 'zzz';<BR>alert( obj2.x.xxx); // Get "zzz"<BR>alert(obj1.x.xxx); // Get "zzz"<BR></script>

obj1 has the "x" attribute, but this attribute is an object. Modifications to "x" in obj2 will also affect obj1, which may cause errors that are difficult to find.

Implementation of deep copy

If we want to implement "deep copy", when the copied object is an array or object, we should call extend recursively. The following code is a simple implementation of "deep copy":

Copy code The code is as follows:

$ = {
extend : function(deep, target, options) {
for (name in options) {
copy = options[name];
if (deep && copy instanceof Array) {
                 target[name] = $.extend(deep, [], copy);
                                                                                                       );
} else {
target[name] = options[name];
}
}
return target;
}
};

It is divided into three situations:
1. When the attribute is an array, initialize target[name] to an empty array, and then call extend recursively;
2. When the attribute is an object, then target[ name] is initialized as an empty object, and then recursively calls extend;
3. Otherwise, copy the properties directly.
The test code is as follows:


Copy code The code is as follows:

<script><BR>obj1 = { a : 'a', b : 'b' };<BR> obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' };<BR>$.extend(true, obj1, obj2);<BR>alert(obj1.x.xxx ); // Get "xxx"<BR>obj2.x.xxx = 'zzz';<BR>alert(obj2.x.xxx); // Get "zzz"<BR>alert(obj1.x.xxx) ; // Get "xxx"<BR></script>


Now if deep copy is specified, modifications to obj2 will not affect obj1; however, there are still some problems with this code, such as "instanceof Array" may be incompatible in IE5. The implementation in jQuery is actually a bit more complex.

More complete implementation

The following implementation will be closer to extend() in jQuery:

Copy code The code is as follows:

$ = function() {
    var copyIsArray,
        toString = Object.prototype.toString,
        hasOwn = Object.prototype.hasOwnProperty;

    class2type = {
        '[object Boolean]' : 'boolean',
        '[object Number]' : 'number',
        '[object String]' : 'string',
        '[object Function]' : 'function',
        '[object Array]' : 'array',
        '[object Date]' : 'date',
        '[object RegExp]' : 'regExp',
        '[object Object]' : 'object'
    },

    type = function(obj) {
        return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
    },

    isWindow = function(obj) {
        return obj && typeof obj === "object" && "setInterval" in obj;
    },

    isArray = Array.isArray || function(obj) {
        return type(obj) === "array";
    },

    isPlainObject = function(obj) {
        if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
            return false;
        }

        if (obj.constructor && !hasOwn.call(obj, "constructor")
                && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
            return false;
        }

        var key;
        for (key in obj) {
        }

        return key === undefined || hasOwn.call(obj, key);
    },

    extend = function(deep, target, options) {
        for (name in options) {
            src = target[name];
            copy = options[name];

            if (target === copy) { continue; }

            if (deep && copy
                    && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if (copyIsArray) {
                    copyIsArray = false;
                    clone = src && isArray(src) ? src : [];

                } else {
                    clone = src && isPlainObject(src) ? src : {};
                }

                target[name] = extend(deep, clone, copy);
            } else if (copy !== undefined) {
                target[name] = copy;
            }
        }

        return target;
    };

    return { extend : extend };
}();


首先是 $ =  function(){...}();这种写法,可以理解为与下面的写法类似:
复制代码 代码如下:

func = function(){...};
$ =  func();

That is, execute the function immediately and assign the result to $. This way of writing can use function to manage scope and prevent local variables or local functions from affecting the global scope. In addition, we only want users to call $.extend() and hide the internally implemented functions, so the final returned object only contains extend:
Copy code The code is as follows:

return { extend : extend };

Next, let’s look at the difference between the extend function and the previous one. First There is an extra sentence:
Copy code The code is as follows:

if (target == = copy) { continue; }

This is to avoid infinite loops. If the attribute copy to be copied is the same as the target, that is, copying "self" to "own attribute" may lead to failure. Anticipated cycle.

Then the way to determine whether the object is an array:

Copy the code The code is as follows:

type = function(obj) {
return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
},
isArray = Array.isArray || function(obj) {
          return type(obj) === "array";
    }

If the browser has a built-in Array.isArray implementation, use the browser Its own implementation, otherwise the object will be converted to String to see if it is "[object Array]".

Finally, let’s look at the implementation of isPlainObject sentence by sentence:

Copy the code The code is as follows:

if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
return false;
}

if obj.nodeType is defined, indicating that this is a DOM element; this code indicates that deep copying will not be performed in the following four situations:
1. The object is undefined;
2. When converted to String, it is not "[object Object]" ";
3. obj is a DOM element;
4. obj is window.
The reason why DOM elements and windows are not deep copied may be because they contain too many attributes; especially for the window object, all variables declared in the global domain will be its attributes, not to mention the built-in attributes.

Next are the tests related to the constructor:

Copy the code The code is as follows:

if (obj.constructor && !hasOwn.call(obj, "constructor")
                                                                                                                               🎜>

If the object has a constructor, but it is not its own attribute, it means that the constructor is inherited through prototye. In this case, deep copying is not performed. This can be understood by combining the following code:


Copy code The code is as follows: var key;
for (key in obj) {
}
return key === undefined || hasOwn.call(obj, key);


These codes are Used to check whether the properties of the object are all its own, because when traversing the object's properties, it will start from its own properties, so you only need to check whether the last property is its own.
This means that if the object inherits the constructor or attributes through prototype, the object will not be deeply copied; this may also be considering that such objects may be complex, in order to avoid introducing uncertain factors or copying a large number of attributes. As for the processing that takes a lot of time, it can be seen from the function name that only "PlainObject" performs deep copying.
If we use the following code to test:



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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft