什么是高階函數(shù)
高階函數(shù)的維基百科定義:至少滿足以下條件之一:
- 接受一個或多個函數(shù)作為輸入;
- 輸出一個函數(shù);
function add (x, y, fn) {
return fn(x) + fn(y);
}
var x = -5,
y = 6,
fn = Math.abs
add(x, y, fn) // 11
高階函數(shù)的好處
// 正常函數(shù)
function isType (obj, type) {
return Object.prototype.toString.call(obj).includes(type)
}
let type = 'xxx'
let is = true
console.log(isType(type, 'String')) // true
console.log(isType(type, 'Boolean')) // false
console.log(isType(is, 'Bolean')) // false,這里因為寫錯了才為 false
// 假如不小心把 Boolean 寫錯了 Bolean,沒注意,這也不會報錯還會安裝平常返回判斷,但是這可能是錯的,很多時候這種錯誤是不容易發(fā)現(xiàn)
其實可以換種寫法,但是注意??寫類型列表時沒有寫錯就可以避免上面的情況
下面是高階函數(shù)寫法
// 高階函數(shù)
function isType (type) {
return function (obj) {
return Object.prototype.toString.call(obj).includes(type)
}
}
const types = ['String', 'Object', 'Array', 'Null', 'Undefined', 'Boolean']
let fns = {}
types.forEach(type => fns[`is${type}`] = isType(type))
let type = 'xxx'
let is = true
console.log(fns.isString(type)) // true
console.log(fns.isBoolean(type)) // false
console.log(fns.isBolean(type)) // fns.isBolean is not a function
// 這里一樣是把 Boolean 寫成了 Bolean,但是這里就報錯讓我們可以發(fā)現(xiàn)這里寫錯了,而不是像上面那樣,還以為是正常的