extend
angular.extend(dst, src);
说明:
依次将第二个参数及后续的参数的第一层属性(不管是简单属性还是对象)拷贝赋给第一个参数的第一层属性,即如果是对象,则是引用的是同一个对象,并返回第一个参数对象。src可以有多个。
angular.extend返回dst的引用。如下图,修改了temp中某个值,dst中同样会变。
不是深拷贝,多个src时,后续的src会覆盖前面src中存在的相同<strong>对象</strong>。如下图,src2中的c会覆盖src中的c。对象完全覆盖,不会考虑对象里面的值。
Note: Keep in mind that angular.extend
does not support recursive merge (deep copy). Use angular.merge
for this.
代码:
$scope.src = {
a: 'A',
b: 'B',
c: {
d: 'D',
e: {
f: 'F'
}
}
};
$scope.src2 = {
c: {
src2: 'D',
e: {
src2: 'src2',
f: 'F'
}
}
};
$scope.dest = {
A: 'a'
};
$scope.temp = angular.extend($scope.dest, $scope.src, $scope.src2);
$scope.change = function(){
$scope.temp.A = 'changed';
}
效果:
src: {"a":"A","b":"B","c":{"d":"D","e":{"f":"F"}}}
src2: {"c":{"src2":"D","e":{"src2":"src2","f":"F"}}}
temp: {"A":"a","a":"A","b":"B","c":{"src2":"D","e":{"src2":"src2","f":"F"}}}
dest: {"A":"a","a":"A","b":"B","c":{"src2":"D","e":{"src2":"src2","f":"F"}}}
点击button后:
src: {"a":"A","b":"B","c":{"d":"D","e":{"f":"F"}}}
src2: {"c":{"src2":"D","e":{"src2":"src2","f":"F"}}}
temp: {"A":"changed","a":"A","b":"B","c":{"src2":"D","e":{"src2":"src2","f":"F"}}}
dest: {"A":"changed","a":"A","b":"B","c":{"src2":"D","e":{"src2":"src2","f":"F"}}}
merge
angular.merge(dst, src);
说明:
和extend的区别就是merge是深拷贝。
如下图,在extend中,src中的c对象会被src2中的c对象覆盖;在merge中,会将两个源中的对象都拷贝,如src中c对象中的d,如果两个源中存在相同对象,并且相同对象中存在相同key,key对应的值会被后者覆盖。
代码:
$scope.src = {
a: 'A',
b: 'B',
c: {
d: 'D',
e: {
f: 'F'
}
}
};
$scope.src2 = {
c: {
src2: 'D',
e: {
src2: 'src2',
f: 'FFFFF'
}
}
};
$scope.dest = {
A: 'a'
};
$scope.temp = angular.merge($scope.dest, $scope.src, $scope.src2);
$scope.change = function(){
$scope.temp.A = 'changed';
}
效果:
src: {"a":"A","b":"B","c":{"d":"D","e":{"f":"F"}}}
src2: {"c":{"src2":"D","e":{"src2":"src2","f":"FFFFF"}}}
temp: {"A":"a","a":"A","b":"B","c":{"d":"D","e":{"f":"FFFFF","src2":"src2"},"src2":"D"}}
dest: {"A":"a","a":"A","b":"B","c":{"d":"D","e":{"f":"FFFFF","src2":"src2"},"src2":"D"}}
点击button后
src: {"a":"A","b":"B","c":{"d":"D","e":{"f":"F"}}}
src2: {"c":{"src2":"D","e":{"src2":"src2","f":"FFFFF"}}}
temp: {"A":"changed","a":"A","b":"B","c":{"d":"D","e":{"f":"FFFFF","src2":"src2"},"src2":"D"}}
dest: {"A":"changed","a":"A","b":"B","c":{"d":"D","e":{"f":"FFFFF","src2":"src2"},"src2":"D"}}
网友评论