Replace a one javascript object with another object

I'm using angularjs and it took me some time to find out how to copy an object to another object. Normally you'll get an objects clone by calling clone or here in angular copy:

var targetObj = angular.copy(sourceObj);

This gives you a new cloned instance (with a new reference) of the source object. But a quick look into the docs reveals the second parameter of copy:

angular.copy(sourceObj, targetObj)

This way you can override a target object with the fields and methods of the source and also keep the target objects reference.


In JavaScript objects are passed by reference, never by value. So:

var objDemo, objDemoBackup;
objDemo = {
    sub_1: "foo";
};
objDemoBackup = objDemo;
objDemo.sub_2 = "bar";
console.log(objDemoBackup.sub_2);   // "bar"

To get a copy, you must use a copy function. JavaScript doesn't have one natively but here is a clone implementation: How do I correctly clone a JavaScript object?

var objDemo, objDemoBackup;
objDemo = {
    sub_1: "foo";
};
objDemoBackup = clone(objDemo);
objDemo.sub_2 = "bar";
console.log(objDemoBackup.sub_2);   // undefined