Keywords: JavaScript Object Copying | Reference vs Copy | jQuery.extend | Deep Copy vs Shallow Copy | JSON Serialization
Abstract: This article provides an in-depth exploration of the fundamental mechanisms of variable assignment in JavaScript, focusing on the distinction between object references and actual copies. Through detailed analysis of assignment operator behavior characteristics and practical solutions including jQuery.extend method and JSON serialization, it systematically explains the technical principles and application scenarios of shallow copy and deep copy. The article contains complete code examples and comparative analysis to help developers thoroughly understand the core concepts of JavaScript object copying.
The Nature of JavaScript Variable Assignment Mechanism
In JavaScript programming, understanding the underlying mechanism of variable assignment is crucial. Many developers mistakenly believe that using the equals operator creates independent copies of data, but in reality, this only creates new references to the same data. When dealing with JSON objects or other complex data structures, this misunderstanding often leads to unexpected behaviors.
Practical Manifestation of Reference Assignment
Consider the following typical scenario: a developer needs to retrieve JSON data from a hidden form field and assign it to two different variables. The initial code implementation is as follows:
var a = $('#some_hidden_var').val(),
b = a;
At this point, variables a and b actually point to the same object in memory. Any modification to the object content through one variable will immediately reflect on the other variable, as they share the same underlying data.
Analysis of Restoration Operation Pitfalls
During application runtime, the value of variable b is continuously updated through a mousemove event handler. When the user clicks the revert button, the expectation is to restore b to its initial state:
$('#revert').on('click', function(e){
b = a;
});
However, this operation is actually ineffective. Since a and b always reference the same object, the assignment statement b = a is equivalent to b = b, which does not produce any actual data separation.
Correct Implementation of Object Cloning
To achieve true object copying, it is necessary to create completely new object instances. Using object literal syntax can create shallow copies:
b = { key1: a.key1, key2: a.key2 };
This method is suitable for simple objects but still has limitations for complex nested structures. A more universal solution is to use jQuery's $.extend method.
Detailed Explanation of jQuery.extend Method
The jQuery library provides powerful object extension functionality, supporting two copy modes:
Shallow copy implementation:
b = $.extend({}, a);
Deep copy implementation:
b = $.extend(true, {}, a);
Technical Comparison Between Shallow Copy and Deep Copy
Shallow copy only duplicates the top-level properties of an object. For nested objects or arrays, the new object still retains references to the original nested structures. Consider the following example object:
var obj = {
w: 123,
x: {
y: 456,
z: 789
}
};
After performing shallow copy:
var copy = $.extend({}, obj);
copy.w = 321;
copy.x.y = 654;
Modifying copy.w does not affect obj.w because primitive values are directly copied. However, modifying copy.x.y simultaneously changes obj.x.y because the nested object x remains a shared reference.
Comprehensive Solution of Deep Copy
Deep copy recursively traverses all nested levels, creating independent copies for each sub-object. This method ensures that modifying any part of the copy does not affect the original object, providing complete data isolation.
JSON Serialization Alternative
Another method to implement deep copy is using JSON serialization:
var newInstance = JSON.parse(JSON.stringify(firstInstance));
This method is simple and effective but requires attention to circular reference situations and loses information about special types such as functions and dates.
Modern JavaScript Copying Solutions
In ES6 and later versions, the Object.assign method can be used to implement shallow copy:
b = Object.assign({}, a);
For more complex copying needs, consider implementing custom deep copy functions or using third-party libraries.
Extension of Practical Application Scenarios
In business system development, the need for object copying is very common. For example, in a ticket processing system, when a user selects to reject an option, it is necessary to copy relevant variable values and rejection reasons to journal fields. Correct copying mechanisms ensure data consistency and integrity.
The implementation logic can be expressed as:
if(current.variables.xyz == 'rejected' && current.rejection_reason != '') {
var journalData = $.extend(true, {}, {
variable: current.variables.xyz,
reason: current.rejection_reason
});
// Save journalData to target table
}
Best Practices Summary
When choosing a copying strategy, the following factors should be considered: complexity of data structure, performance requirements, browser compatibility. For most application scenarios, deep copy is the safest choice, capable of avoiding unexpected reference sharing issues. Developers should weigh the advantages and disadvantages of various solutions according to specific needs and choose the most appropriate copying method.