gpt4 book ai didi

javascript - 为什么以及何时使用 angular.copy? (深拷贝)

转载 作者:IT王子 更新时间:2023-10-29 02:38:19 25 4
gpt4 key购买 nike

我一直将从服务接收的所有数据直接保存到局部变量、 Controller 或范围。我想应该被认为是浅拷贝,对吗?

Example:

DataService.callFunction()
.then(function(response) {
$scope.example = response.data;
});

最近我被告知要使用 angular.copy 来创建深拷贝。

$scope.example = angular.copy(response.data);

但是,当我的 Angular 应用程序使用深层复制信息时,它似乎以相同的方式工作。 使用深拷贝 (angular.copy) 有什么特别的好处吗?您能给我解释一下吗?

最佳答案

使用 angular.copy将对象或数组的值分配给另一个变量时,该 object 值不应更改。

没有深层复制或使用angular.copy,更改属性值或添加任何引用同一对象的新属性更新所有对象

var app = angular.module('copyExample', []);
app.controller('ExampleController', ['$scope',
function($scope) {
$scope.printToConsole = function() {
$scope.main = {
first: 'first',
second: 'second'
};

$scope.child = angular.copy($scope.main);
console.log('Main object :');
console.log($scope.main);
console.log('Child object with angular.copy :');
console.log($scope.child);

$scope.child.first = 'last';
console.log('New Child object :')
console.log($scope.child);
console.log('Main object after child change and using angular.copy :');
console.log($scope.main);
console.log('Assing main object without copy and updating child');

$scope.child = $scope.main;
$scope.child.first = 'last';
console.log('Main object after update:');
console.log($scope.main);
console.log('Child object after update:');
console.log($scope.child);
}
}
]);

// Basic object assigning example

var main = {
first: 'first',
second: 'second'
};
var one = main; // same as main
var two = main; // same as main

console.log('main :' + JSON.stringify(main)); // All object are same
console.log('one :' + JSON.stringify(one)); // All object are same
console.log('two :' + JSON.stringify(two)); // All object are same

two = {
three: 'three'
}; // two changed but one and main remains same
console.log('main :' + JSON.stringify(main)); // one and main are same
console.log('one :' + JSON.stringify(one)); // one and main are same
console.log('two :' + JSON.stringify(two)); // two is changed

two = main; // same as main

two.first = 'last'; // change value of object's property so changed value of all object property

console.log('main :' + JSON.stringify(main)); // All object are same with new value
console.log('one :' + JSON.stringify(one)); // All object are same with new value
console.log('two :' + JSON.stringify(two)); // All object are same with new value
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="copyExample" ng-controller="ExampleController">
<button ng-click='printToConsole()'>Explain</button>
</div>

关于javascript - 为什么以及何时使用 angular.copy? (深拷贝),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33043850/

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