Click here to Skip to main content
16,022,896 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,
1.I want to know what is different between:
var sourceItem = service.getItemByID(id);

$scope.item = angular.copy(sourceItem);
and
$scope.item = sourceItem;

2.I read topics about service and factory . Seems they are only different about coding style. Is it right ?

Thanks.
Posted

1 solution

Of course they are different: https://docs.angularjs.org/api/ng/function/angular.copy[^].

The result of this function is a deep copy of the original object. They are referentually different, because the two objects will exist as independent objects which reside in different fragments of memory. If you modify any property of any of the objects in the object graph referenced by either source or resulting reference, the other object will remain intact.

This is not what happens if you simply assign one object to another. Consider this:
JavaScript
var a = {a:1, b:2, c:3}
var b = a
b.a = 13
// now a.a == 13
// a and b are two different variables
// referencing the same object

Compare it with
JavaScript
var a = {a:1, b:2, c:3}
var b = {} // not a, different reference
b.a = a.a; b.b = a.b; b.c = a.c;
b.a = 13
// still a.a == 1
// a and b are independent objects
Understanding of reference and value objects lie in the very heart of general programming. You need to understand such things perfectly, to do nearly any kind of programming.

I used an example where deep copy is no different from shallow copy. Deep copy is needed when element of some objects are also some non-primitive objects, and so on. Shallow copy keeps the referentially identical properties, and deep copy clones all objects of all properties recursively.

—SA
 
Share this answer
 
v7

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900