What is the difference between angular.copy() and an assignment (=)?

前端 未结 5 854
遇见更好的自我
遇见更好的自我 2020-12-02 17:02

I want to assign some values when a button click event happens via event parameter:

$scope.update = function(context) {
    $scope.master = context;
};


        
相关标签:
5条回答
  • 2020-12-02 17:34

    In assignment we share the reference of the object. when we use angular.copy we create a new reference point with the same object details.

    var user1={name:'hello'};
    

    The object {name:'hello'} has a reference point(let's say 123, which is saved in user1; when we write

    var user2=var user1; //reference point of user2 is also 123 
    user2.name="world"; //we update the object in 123
    console.log(user1.name); //answer is "world" because reference object is updated
    

    In case you don't want to update user1 when you change something in user2 we have to create a copy. we can do it like

    var user2=angular.copy(user1);
    

    or

    var user2=Object.assign({},user1);
    
    0 讨论(0)
  • 2020-12-02 17:36

    Simply

    angular.copy() is same as .clone() of jquery which create & returns same object copy with dept. (call by value)

    = it does assign the value with its reference value(call by reference),

    a = b in this a will be b value is assigned to a, but if both a & b are array then changes in a will reflect in b & vice versa.

    0 讨论(0)
  • 2020-12-02 17:47

    = represents a reference whereas angular.copy() creates a new object as a deep copy.

    Using = would mean that changing a property of contextwould change the corresponding property of $scope.master or vice versa.

    Using angular.copy() the two objects would remain seperate and changes would not reflect on each other.

    0 讨论(0)
  • 2020-12-02 17:47

    When you manipulate primitive types (like int) in Javascript, = and angular.copy are the same as any assignment results in copying the value of the variable.

    When you manipulate objects in Javascript, = assign a reference to the existing object to the variable and angular.copy is copying, that means creating a new object with the same properties and values and assigning the new object's reference to the variable.

    0 讨论(0)
  • 2020-12-02 17:50

    As can be read here angular.copy() performs a deep copy (cf. "clone") of the argument - essentially creating a new object - whereas using the assignment operator = just assigns reference's.

    Thus in the latter case, if you we're to change something in $scope.master you would also change context.

    Cheers,

    0 讨论(0)
提交回复
热议问题