Knowing the difference between a value being assinged by reference in contrast to being assigned by value is crucial. In Javascript primitive types like strings or numbers are always assigned by value. So assigning a variable A to a variable B results in variable B containing a “real” copy of variable A. Changing the value of variable B afterwards won’t change the value of variable A.
However, when assigning an object A to an object B in Javascript, object_b is assigned by reference, meaning that both variables point to the same object. In this case changing a property in object B will change the property in object A as well. See the following example:
var object_a = {url:"webdevwonders.com"}; var object_b = object_a; object_b.url = "google.com"; alert(object_a.url); // Alerts "google.com"
Object A’s property “url” has changed to “google.com”, because the variable object_a points to the same object as variable object_b does. That’s nice but in quite a lot of cases a real (or deep) copy is what you want. The solution to the problem is to loop over each property of object A and assign its value to the property of object B. That is what the following code accomplishes:
var object_a = {url:"webdevwonders.com"}; var object_b = {}; for (var prop in object_a) { object_b[prop] = object_a[prop]; } object_b.url = "google.com"; alert(object_a.url); // Alerts "webdevwonders.com"
If you’re using jQuery there’s a far more elegant way to solve the problem:
var object_a = {url:"webdevwonders.com"}; var object_b = jQuery.extend(true, {}, object_a); object_b.url = "google.com"; alert(object_a.url); // Alerts "webdevwonders.com"