gpt4 book ai didi

javascript - angular.copy() 和 Object.assign() 有什么区别?

转载 作者:行者123 更新时间:2023-11-29 17:49:07 24 4
gpt4 key购买 nike

我想知道是否有任何差异。

我可以看到 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>

最佳答案

所以主要区别在于 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.

关于javascript - angular.copy() 和 Object.assign() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45833467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com