This article shares the shallow copy and deep copy code of JavaScript objects for your reference. The specific content is as follows
1. Light copy
Copy means copying all the properties of the parent object to the child object.
The following function is copying:
var Chinese = { nation:'China'}var Doctor = { career:'Doctor'} function extendCopy(p) { var c = {}; for (var i in p) { c[i] = p[i]; } c.uber = p; return c; }When using it, write this:
var Doctor = extendCopy(Chinese);Doctor.career = 'Doctor';alert(Doctor.nation); // China
However, there is a problem with such a copy. That is, if the property of the parent object is equal to an array or another object, then in fact, the child object only gets a memory address, not a real copy, so there is a possibility that the parent object will be tampered with.
Please see, now add a "Birthplace" property to Chinese, whose value is an array.
Chinese.birthPlaces = ['Beijing','Shanghai','Hong Kong'];
Through the extendCopy() function, the Doctor inherits Chinese.
var Doctor = extendCopy(Chinese);
Then we add a city to the Doctor's "place of birth":
Doctor.birthPlaces.push('Xiamen');
Check out the input results
alert(Doctor.birthPlaces); //Beijing, Shanghai, Hong Kong, Xiamen
alert(Chinese.birthPlaces); //Beijing, Shanghai, Hong Kong, Xiamen
As a result, both birthplaces were changed.
Therefore, extendCopy() just copies basic type data, and we call this copy "shallow copy".
2. Deep copy
Because the shallow and deep copy has such disadvantages, let's take a look at the deep copy next
The so-called "deep copy" means that it can realize the real copy of arrays and objects. Its implementation is not difficult, just call "shallow copy" recursively.
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; }Take a look at how to use it:
var Doctor = deepCopy(Chinese);
Now, add a property to the parent object with the value as an array. Then, modify this property on the child 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 KongThis completes the copy;
$.extend()
$.extend() in jquery is the same.
$.extend( [deep ], target, object1 [, objectN ] )
•deep
Type: Boolean
If true, merge becomes recursive (also called deep copy).
•target
Type: Object
Object extension. This will receive new properties.
•object1
Type: Object
An object that contains additional properties merged into the first parameter.
•objectN
Type: Object
Contains additional attributes to merge into the first parameter
When we provide two or more objects to $.extend(), all properties of the object are added to the target object (target parameter).
If only one parameter is provided to $.extend(), this means the target parameter is omitted. In this case, the jQuery object itself is defaulted to the target object. In this way, we can add new features under the jQuery namespace. This is useful for plugin developers when they want to add new functions to jQuery.
Remember that the target object (first parameter) will be modified and will be returned via $.extend(). However, if we want to keep the original object, we can pass an empty object as the target object:
var object = $.extend({}, object1, object2);
By default, the merge operation via $.extend() is not recursive; if the property of the first object itself is an object or array, then it will override a property completely with the same key of the second object. These values will not be merged. This can be understood by checking the value of banana in the example below. However, if true is used as the first argument to the function, recursive merges will be performed on the object.
Warning: Passing false for the first parameter is not supported.
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 in recursive manner 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 defaults and options objects and do not modify the defaults object. This is a commonly used plug-in development model.
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 determines whether objects are equal
In Javascript, equality operations include "==","==="consistency. There is no need to be a majority of the differences between the two. In this article, we will talk about how to determine whether two objects are equal? You might think that if two objects have the same properties and their properties have the same values, then the two objects are equal. Then let’s use an example to demonstrate:
var obj1 = { name: "Benjamin", sex : "male"}var obj2 = { name: "Benjamin", sex : "male"}//Outputs: false secondso.log(obj1 == obj2);//Outputs: false secondso.log(obj1 === obj2);From the example above, we can see that whether you use "==" or "==", false is returned. The main reason is that the basic types string and number are compared by values, while objects (Date, Array) and ordinary objects are compared by the address in memory pointed to by pointers. See 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);The above example returns true because the pointers of obj1 and ob3 point to the same address in memory. It is similar to the concept of value passing and reference passing in object-oriented languages (Java/C++). Because, if you want to determine whether two objects are equal, you must be clear, are you trying to determine whether the properties of the two objects are the same, or whether the values corresponding to the properties 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 console.log(p1.sayHi() === p2.sayHi()); //trueThe above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.