作为值的函数

 1 function createComparisonFunction(propertyName) {
 2             return function (object1, object2) {
 3                 var value1 = object1[propertyName];
 4                 var value2 = object2[propertyName];
 5 
 6                 if (value1 < value2) {
 7                     return -1;
 8                 } else if (value1 > value2) {
 9                     return 1;
10                 } else {
11                     return 0;
12                 }
13             };
14         }
15 
16         var data = [
17             {name:"Zachary", age:28},
18             {name:"Nicholas", age:29}
19         ];
20 
21         data.sort(createComparisonFunction("name"));
22         console.log(data[0].name);
23 
24         data.sort(createComparisonFunction("age"));
25         console.log(data[0].name);
posted @ 2012-03-12 15:13  小猩猩君  阅读(163)  评论(0编辑  收藏  举报