This article mainly introduces the shallow copy and deep copy code of JavaScript objects in detail, which has some reference value, interested friends can refer to this article to share with you the shallow copy and deep copy code of JavaScript objects for your reference. The specific content is as follows:
1. Shallow copy
Copying copies all attributes of the parent object to the sub-object.
The following function is used for copying:
Var Chinese = {nation: 'China'} var Doctor = {career: 'docker'} function extendCopy (p) {var c = {}; for (var I in p) {c [I] = p [I];} c. uber = p; return c ;}
Write as follows:
Var Doctor = extendCopy (Chinese); Doctor. career = 'Doc'; alert (Doctor. nation); // China
However, there is a problem with such a copy. That is, if the attribute of the parent object is equal to an array or another object, in fact, the sub-object only obtains a memory address rather than a real copy, so there is a possibility that the parent object will be tampered.
Now, add the "Birthplace" attribute to Chinese. Its value is an array.
Chinese. birthPlaces = ['beijing', 'shanghai', 'Hong Kong '];
Using the extendCopy () function, Doctor inherits Chinese.
Var Doctor = extendCopy (Chinese );
Then, we add a city for Doctor's "Birthplace:
Doctor. birthPlaces. push ('xiamen ');
Let's take a look at the input results.
Alert (Doctor. birthPlaces); // Beijing, Shanghai, Hong Kong, Xiamen
Alert (Chinese. birthPlaces); // Beijing, Shanghai, Hong Kong, Xiamen
The result is that both locations were changed.
Therefore, extendCopy () only copies the basic types of data. We call this copy a "shortest copy ".
2. Deep copy
Because the downloading of copying copies is so flawed, let's take a look at the deep copy.
The so-called "Deep copy" means to copy arrays and objects in the true sense. Its implementation is not difficult, as long as it recursively calls the "Shallow copy.
function deepCopy(p, c) { var c = c || {}; for (var i in p) { if (typeof p[i] === 'object') { c[i] = (p[i].constructor === Array) ? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } return c; }
Let's take a look at the usage:
Var Doctor = deepCopy (Chinese );
Now, add an attribute to the parent object and the value is an array. Then, modify this attribute on the sub-object:
Chinese. birthPlaces = ['beijing', 'shanghai', 'Hong Kong ']; Doctor. birthPlaces. push ('xiamen '); alert (Doctor. birthPlaces); // Beijing, Shanghai, Hong Kong, Xiamen alert (Chinese. birthPlaces); // Beijing, Shanghai, Hong Kong
This completes the copy;
$. Extend ()
In jquery, $. extend () is like.
$. Extend ([deep], target, object1 [, objectN])
• Deep
Type: Boolean
If it is true, it is merged into recursion (also called Deep copy ).
• Target
Type: Object
Object extension. This will receive new attributes.
• Object1
Type: Object
An object that includes additional attributes and merges them into the first parameter.
• ObjectN
Type: Object
Include additional attributes and merge them to the first parameter.
When we provide two or more objects to $. extend (), all attributes of the object are added to the target object (target parameter ).
If only one parameter is provided to $. extend (), this means that the target parameter is omitted. In this case, the jQuery object itself is the default target object. In this way, we can add new functions under the namespace of jQuery. This is useful for plug-in developers who want to add new functions to jQuery.
Remember that the target object (the first parameter) will be modified and will be returned through $. extend. However, if we want to retain the original object, we can pass an empty object as the target object:
Var object = $. extend ({}, object1, object2 );
By default. the extend () Merge operation is not recursive. If the attribute of the first object itself is an object or array, It will completely overwrite an attribute with the same key of the second object. These values are not merged. You can understand this by checking the banana value in the following example. However, if true is used as the first parameter of the function, recursive merge is performed on the object.
Warning the first parameter cannot be passed false.
1. merge two objects and modify the first object.
var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97};var object2 = { banana: { price: 200 }, durian: 100}; // Merge object2 into object1$.extend( object1, object2 ); // Assuming JSON.stringify - not available in IE<8console.log( JSON.stringify( object1 ) );//{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
2. merge two objects recursively and modify the first object.
var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97};var object2 = { banana: { price: 200 }, durian: 100}; // Merge object2 into object1, recursively$.extend( true, object1, object2 ); // Assuming JSON.stringify - not available in IE<8console.log( JSON.stringify( object1 ) );//{"apple":0,"banana":{"weight":52,"price":200},"cherry":97,"durian":100}
3. Merge the ults and options objects without modifying the defaults object. This is a common plug-in development mode.
var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" }; // Merge defaults and options, without modifying defaultsvar settings = $.extend( {}, defaults, options ); console.log(JSON.stringify( defaults ));console.log(JSON.stringify( options ));console.log(JSON.stringify( settings ));//defaults -- {"validate":false,"limit":5,"name":"foo"}//options -- {"validate":true,"name":"bar"}//settings -- {"validate":true,"limit":5,"name":"bar"}
Javascript checks whether objects are equal
Equality operations in Javascript include "=", "=", and so on. The two are different from each other. In this article, we will explain how to determine whether two objects are equal? You may think that if two objects have the same attributes and their attributes have the same values, the two objects will be equal. The following is an example to illustrate:
var obj1 = { name: "Benjamin", sex : "male"} var obj2 = { name: "Benjamin", sex : "male"} //Outputs: falseconsole.log(obj1 == obj2); //Outputs: falseconsole.log(obj1 === obj2);
As shown in the preceding example, "=" or "=" "is returned. The main reason is that the basic types of string and number are compared by values, while the objects (Date, Array) and common objects are compared by the addresses in the memory pointed to by pointers. Let's look at the following example:
var obj1 = { name: "Benjamin", sex : "male"}; var obj2 = { name: "Benjamin", sex : "male"}; var obj3 = obj1; //Outputs: trueconsole.log(obj1 == obj3); //Outputs: trueconsole.log(obj1 === obj3); //Outputs: falseconsole.log(obj2 == obj3); //Outputs: falseconsole.log(obj2 === obj3);
In the preceding example, true is returned because the pointers of obj1 and ob3 point to the same address in the memory. It is similar to the concept of Intermediate Value Transfer and reference transfer in an object-oriented language (Java/C ++. Because, if you want to determine whether two objects are equal, you must be clear. Do you want to determine whether the attributes of the two objects are the same, whether the values of the attributes are the same, or what?
function person(name) { this.name=name; } var p1 = new person("p1"); var p2 = new person("p2"); console.log(p1 == p2); //false person.prototype.sayHi = function() { // do sayHi here } console.log(p1.sayHi() == p2.sayHi()); //true console.log(p1.sayHi() === p2.sayHi()); //true
The above is all of the content in this article. I hope it will be helpful for everyone's learning and support for PHP's Chinese Web.
For more details about the js object shortest copy and deep copy, refer to the PHP Chinese website!