我最近在Angular教程中注意到以下代码...
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName: "John", lastName: "Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>
关于这一行:$scope.user = angular.copy($scope.master);
,是否可以简化为:$scope.user = $scope.master;
看到$scope.master
在这种情况下将成为不可变常量?
答案 0 :(得分:3)
当您使用对象在JavaScript中执行angular.copy
时,您只是分配引用,而不是创建新对象(新引用)。在这种情况下,var obj1 = {}, var obj2 = {}
obj1 !== obj2; // true
obj1 = obj2;
obj1 === obj2; // true
obj1 = angular.clone(obj2);
obj1 !== obj2; // true
会创建一个新对象。
在代码中:
{{1}}