angular.copy()和Object.assign()之间有什么区别?

时间:2017-08-23 07:37:24

标签: javascript angularjs copy clone

我想知道是否存在任何差异。

我可以看到Object.assign()只是克隆对象,这样做,无论我是否更改原始对象,克隆对象都将保持其值。

尽管如此,我发现函数没有被复制,只有可枚举的属性。

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>

1 个答案:

答案 0 :(得分:3)

因此主要区别在于angular.copy将执行深层复制,而Object.assign将不执行此操作。尝试在您的示例中运行以下代码:

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

$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.