關於angular.extend的用法

ng中的ng-function中會有些方法,便於咱們進行js代碼的編寫javascript

關於angular.extend(dst, src);經過從src對象複製全部屬性到dst來擴展目標對象dst。你能夠指定多個src對象。html

注意:angular.extend(....)只是簡單的對象之間的相互引用,java

 

經典的demo ;angularjs

<!DOCTYPE html>
<html ng-app="extendApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
</head>
<body>

<div ng-controller="extendController">

<button ng-click="extend()">點擊我!</button>

</div>
</body>
</html> 數組

<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();
// $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>app

結果:spa

  I can only cry!
  I can earn money!
  I hate you!
  I hate you!code

 

 

拓展:關於對象,數組的複製,咱們能夠進一步的瞭解angular.copy();的使用方法htm

相關文章
相關標籤/搜索