$.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".
If you only need to implement shallow copy, you can use something like the following:
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"):
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.
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":
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.
<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:
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: