2

I would like to know if there are any differences.

I can see that Object.assign() just clones the object, and doing so, no matter if I change the original object, the cloned object will maintain its values.

Nevertheless, I see that functions are not copied, only enumerable properties.

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('myCtrl', function($scope, $log) {
  $scope.obj1 = {
    prop1: () => "a string",
    prop2: [1, 2, 3],
    prop3: new Date(),
    prop4: {
      a: 1
    }
  };
  $scope.obj2 = {
    "$scope.obj1": $scope.obj1,
   "angular.copy Obj1": angular.copy($scope.obj1)
};

$scope.angularClone = angular.copy($scope.obj1);
$scope.es6clone = Object.assign({}, $scope.obj1) ;
$scope.obj1.prop2= "newProp2"
$scope.obj1 = "destroyed obj1";

});
<!doctype html>
<html ng-app="ui.bootstrap.demo">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
</head>

<body>

  <div ng-controller="myCtrl">
    <h3>obj1</h3> {{obj1}}
    <hr>
    <h3>obj2</h3> {{obj2}}
    <hr>
    <h3>angularClone</h3> {{angularClone}}
    <hr>
    <h3>es6clone</h3> {{es6clone}}
    <hr>
  </div>
</body>

</html>

2
  • See this SO post: stackoverflow.com/questions/29749433/… Commented Aug 23, 2017 at 7:39
  • I've seen it, but in the snippet you can see that the behavior is different than a plain assignment Commented Aug 23, 2017 at 7:41

1 Answer 1

2

So the main difference is that angular.copy will do deep copy and Object.assign will not do it. Try in your example to run following code:

$scope.angularClone = angular.copy($scope.obj1);
$scope.angularClone.prop4.a = 5;
$scope.obj1.prop4.a; // Will return 1

and

$scope.es6clone = Object.assign({}, $scope.obj1) ;
$scope.es6clone.prop4.a = 4;
$scope.obj1.prop4.a; // Will return 4 because object assign doesn't create deep copy.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.