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

前端 未结 5 878
遇见更好的自我
遇见更好的自我 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);
    

提交回复
热议问题