函数作为另一个函数的参数还是作为返回值,这两种应用情形都体现了在javascript中,函数是一个对象,是一个value.
1. 函数作为返回结果
function createCompareFunction(propertyName) {
return function compareFunction(object1, object2, propertyName) {
let value1 = object1[propertyName];
let value2 = object2[propertyName];
return value1 < value2 ? -1 :
value1 > value2 ? 1:
0;
};
}
data = [{name:"Amy",age:20},{name:"Sheldon",age:22},{name:"penny",age:21}];
data.sort(createCompareFunction("age"));
console.log(data);

输出结果
2. 函数作为另一个函数的函数
function ask(age, yes, no) {
return age >= 18 ? yes() : no();
}
let age=prompt("How old are you?","");
ask(age,
function(){ alert("Welcome to this website!");},
function(){ alert("Teenagers are not welcomed on the page!");});
网友评论