


Detailed explanation and examples of jQuery.extend() implementation_javascript skills
<script><br>obj1 = { a : 'a', b : 'b' };<br>obj2 = { x : { xxx : 'xxx', yyy : 'yyy' }, y : 'y' }; <p>$.extend(true, obj1, obj2);</p> <p>alert(obj1.x.xxx); // Get "xxx"</p> <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:
$ = {
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"):
<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":
$ = {
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;
}
};
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:
<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:
$ = 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:
return { extend : extend };
Next, let’s look at the difference between the extend function and the previous one. First There is an extra sentence:
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:
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:
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:
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:
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
