Home Web Front-end JS Tutorial Detailed explanation and examples of jQuery.extend() implementation_javascript skills

Detailed explanation and examples of jQuery.extend() implementation_javascript skills

May 16, 2016 pm 05:30 PM

Copy code The code is as follows:

<script type="text/javascript" src= "jquery-1.5.2.js"></script>
<script>
obj1 = { a : 'a', b : 'b' };
obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' };

$.extend(true, obj1, obj2);

alert(obj1.x.xxx); // Get "xxx"

obj2.x.xxx = 'zzz';
alert(obj2.x.xxx); // Get "zzz"
alert(obj1.x.xxx); // Must bring "xxx"
</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 type="text/javascript" src="jquery-extend.js"></script>
<script>
obj1 = { a : 'a', b : 'b' };
obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' };
$.extend(obj1, obj2);
alert(obj1.x.xxx); // Get "xxx"
obj2.x.xxx = 'zzz';
alert( obj2.x.xxx); // Get "zzz"
alert(obj1.x.xxx); // Get "zzz"
</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 type= "text/javascript" src="jquery-extend.js"></script>
<script>
obj1 = { a : 'a', b : 'b' };
obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' };
$.extend(true, obj1, obj2);
alert(obj1.x.xxx ); // Get "xxx"
obj2.x.xxx = 'zzz';
alert(obj2.x.xxx); // Get "zzz"
alert(obj1.x.xxx) ; // Get "xxx"
</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 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 Article Tags

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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

Example Colors JSON File

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

8 Stunning jQuery Page Layout Plugins

10 jQuery Syntax Highlighters 10 jQuery Syntax Highlighters Mar 02, 2025 am 12:32 AM

10 jQuery Syntax Highlighters

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

Build Your Own AJAX Web Applications

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

What is 'this' in JavaScript?

10  JavaScript & jQuery MVC Tutorials 10 JavaScript & jQuery MVC Tutorials Mar 02, 2025 am 01:16 AM

10 JavaScript & jQuery MVC Tutorials

See all articles