js是函数式语言,这意味着我们可以将函数赋值给一个变量,作为函数的参数,作为函数的返回值,看一些例子。
// node higher-order-functions.js
'use strict'
console.log('// Can store a function in a variable')
function average(x, y) {
return (x + y) / 2
}
let f = average
console.log('// Call the function')
let result = f(6, 7)
console.log('result:', result) // 6.5
console.log('// Put another function in the variable')
f = Math.max
result = f(6, 7)
console.log('result:', result) // 7
console.log('// Pass a function to another function')
result = [0, 1, 2, 4].map(Math.sqrt)
console.log('result:', result) // [0, 1, 1.4142135623730951, 2]
返回值例子
function getFunc(type) {
return function (obj) {
return Object.prototype.toString.call(obj) === type;
}
}
let ff = getFunc("[object Array]");
let result = ff([10, 20, 30]);
console.log(result); //true
let ff1 = getFunc("[object Object]");
let dt = new Date();
let result1 = ff1(dt);
console.log(result1); //false