函数作为返回值 function f1 ( ) { console .log("f1函数开始" ); return function ( ) { console .log("我是返回值的函数" ); } } var ff = f1();ff();
function getFunc (type ) { return function (obj ) { return Object .prototype.toString.call(obj) === type; } } var ff = getFunc("[object Array]" );var result = ff([10 , 20 , 30 ]);console .log(result); var ff1 = getFunc("[object Object]" );var dt = new Date ();var result1 = ff1(dt);console .log(result1);
返回值案例 采用时间排序:
function File (name, size, time ) { this .name = name; this .size = size; this .time = time; } var f1 = new File("jack.avi" , "400M" , "1997-12-12" );var f2 = new File("tom.avi" , "200M" , "2017-12-12" );var f3 = new File("xiaosu.avi" , "800M" , "2010-12-12" );var arr = [f1, f2, f3];function getSort (obj1, obj2 ) { if (obj1.time > obj2.time) { return 1 ; } else if (obj1.time == obj2.time) { return 0 ; } else { return -1 ; } } arr.sort(getSort); for (var i = 0 ; i < arr.length; i++) { console .log(arr[i].name + "====>" + arr[i].size + "===>" + arr[i].time); }
以上可以采用时间进行排序,可是如果我需要使用名字或者大小排序的时候有需要修改getSort
方法,这没有达到代码的复用性,因此,对getSort
再次进行封装
function File (name, size, time ) { this .name = name; this .size = size; this .time = time; } var f1 = new File("jack.avi" , "400M" , "1997-12-12" ); var f2 = new File("tom.avi" , "200M" , "2017-12-12" ); var f3 = new File("xiaosu.avi" , "800M" , "2010-12-12" ); var arr = [f1, f2, f3]; function fn (attr ) { return function getSort (obj1, obj2 ) { if (obj1[attr] > obj2[attr]) { return 1 ; } else if (obj1[attr] == obj2[attr]) { return 0 ; } else { return -1 ; } } } var ff = fn("name" ); arr.sort(getSort); for (var i = 0 ; i < arr.length; i++) { console .log(arr[i].name + "====>" + arr[i].size + "===>" + arr[i].time); }