您的位置:首页 > Web前端 > AngularJS

angular.identity

2016-01-25 11:35 531 查看
解释:http://stackoverflow.com/questions/15421502/is-there-any-good-example-of-use-cases-for-angular-identity

看ng文档有个奇怪的方法angular.identity

好像就是你传什么就返回什么。

官方文档给的例子是:

function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};


实际上等价于

function transformer(transformationFn, value) {
if(transformationFn){
return transformationFn(value);
}else{
return angular.identity(value);
}
};


运用场景

// 有下面方法,返回一个数的平方
$scope.square = function(n) {
return n * n
};

//把这个方法作为参数使用

$scope.givemeResult = function(fn, val) {
return (fn || angular.identity)(val);
};

$scope.initVal = 5;
$scope.squareResult = $scope.givemeResult($scope.square, $scope.initVal);


返回25,如果

$scope.squareResult = $scope.givemeResult($scope.square2, $scope.initVal);


因为$scope.square2根本不存在,所以返回5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: