Home > Article > Web Front-end > Comparison and use of clone() and extend() in jQuery
jQuery's clone() method, when I customize an object, for example
var obj = { chart: { type: 'spline', inverted: true }, title: {//标题文字 text: 'Atmosphere Temperature by Altitude' }, ... };
When I want to customize another obj2 and copy the content of obj, I Using
var obj2 = obj.clone();
obviously shows that I ignored that obj is just a object and does not have the clone() method. So it's obviously a wrong demonstration. However, the clone() method that comes with jQuery can no longer meet my needs this time, which is to copy one object to another object, clone(obj);
Shallow-level copy: for non-basicData type, after cloning, the two pointers point to the same memory space. In this case, if one object is operated on, the content of the other object will also change.
Deep copy: Copy every attribute and method of the pointed object to the object pointed to by the new object, just like a copy, so that the new object can be modified or otherwise The operation has no impact on the original object.
Below I give a deep copy method:
var cloneObj = function(obj){ var str, newobj = obj.constructor === Array ? [] : {}; if(typeof obj !== 'object'&& typeof obj !=='function'){ return; }else { for(var i in obj){ newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i]; } } return newobj; }; //克隆 var obj2=clone(obj);
When I want to change some parameters inside, I can use the following method
obj2.title.text = "XXX";
Use the extend() method: Extension means that one or more properties can be extended to an object
to form a union effect. If we are talking about empty objects here, Expanding to an object is equivalent to cloning
$.extend(true,obj,{});
The code to obtain the union effect is as follows
obj2 = $.extend(true,obj,obj2);
When you want to overwrite a parameter, you can choose the same override method as clone(), You can also choose to add the following code in front of
obj2 = $.extend(true,obj,obj2);
:
var obj2 = { title: { text: 'XXX' }, ... }
The above is the detailed content of Comparison and use of clone() and extend() in jQuery. For more information, please follow other related articles on the PHP Chinese website!