AngularJs的angular.extend()方法可以把一个或多个对象中的方法和属性扩展到一个目的对象中,使得这个对象拥有其他对象相同的方法和属性,如下图所示。
angular.extends()方法的第一个参数是要被扩展的对象,后面可以传入一个或多个对象。
如果想要保存一个对象的状态,除了可以调用angular.copy()方法外,还可以把一个空对象{}作为第一个对象传入。
但要注意的是,angular.extends()是非递归的,也就是说:如果扩展的属性中有对象,那么二者同时引用同一个对象!
下面这个例子证实了这个说法:
<!DOCTYPE html> <html ng-app="extendApp"> <head> <meta charset="UTF-8"> <title></title> <script src="../js/angular.js"></script> <script type="text/javascript"> angular.module("extendApp", []) .controller("extendController", function($scope) { $scope.baby = { cry : function() { console.log("I can only cry!"); } } $scope.adult = { earn : function() { console.log("I can earn money!"); }, lover: { love:function() { console.log("I love you!"); } } } $scope.human = {} $scope.hehe = "hehe "; $scope.extend = function() { angular.extend($scope.human, $scope.baby, $scope.adult); $scope.human.cry(); $scope.human.earn(); <!-- 注意,这里修改了lover对象的love()方法,由于extends()方法不是深复制的,$scope.human 和$scope.adult其实引用的是同一个对象--> $scope.human.lover.love = function() { console.log("I hate you!"); } <!-- 这两行都会输出“I hate you !",可怜的adult对象, 他把自己的lover分享给了human! --> $scope.human.lover.love(); $scope.adult.lover.love(); } }); </script> </head> <body> <div ng-controller="extendController"> <button ng-click="extend()">点击我!</button> </div> </body> </html>
控制台的打印结果如下:
- I can only cry!
- I can earn money!
- I hate you!
- I hate you!
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"}}