Friday, January 29, 2016

JAVASCRIPT vs ANGULARJS - copy object by value, not by reference

In JavaScript copy of object is done by reference:
var newObj = Object.create(oldObj); //Modification in newObj would be reflected in oldObj.

JavaScript solution 1: Inline deep copying (if you know its structure)
var newObj = {
   name: source.name,
   type: source.type
}

JavaScript solution 2: Use JSON parse (it could be more slower)
var newObject = JSON.parse(JSON.stringify(oldObject));

Angular way:
var newObject = angular.copy(oldObject);

No comments: