Skip to content

JS 高阶函数

一句话解释高阶函数:把函数作为参数或者返回值的函数。

JS 中部分内置的高阶函数

  • Function.prototype.bind
  • Function.prototype.apply
  • Function.prototype.call
  • Array.prototype.sort
  • Array.prototype.map
  • Array.prototype.filter
  • Array.prototype.reduce

bind/apply/call.call() 是什么意思

例如,bind的一般用法:

javascript
var f1 = function() {
  console.log(this)
  console.log(arguments)
}
var newF1 = f1.bind({ name: 'john' }, 1, 2)
newF1()
// {name: 'john'}
// [1, 2]

推理:

  1. 已知obj.method(a, b, c)等价于obj.method.call(obj, a, b, c)
  2. 假设obj = f1method = bind
  3. 那么f1.bind(a, b, c)等价于f1.bind.call(f1, a, b, c)
  4. 假设a = { name: 'john' }b = 1c = 2
  5. 那么f1.bind({ name: 'john' }, 1, 2)这就是一般的用法,它等价于f1.bind.call(f1, { name: 'john' }, 1, 2)
  6. 因为f1.bind === Function.prototype.bind,那么var bind = Function.prototype.bind,得出bind.call(f1, { name: 'john' }, 1, 2)

bind.call()的用法:接受一个函数、需要绑定的this以及其它参数。

bind.call会调用这个函数,并传入this和其它参数,同时返回一个新的函数。

apply.callcall.call基本同理。

sort/map/filter/reduce.call() 是什么意思

例如,sort的一般用法:

javascript
var arr = [2, 3, 1, 5, 4]
arr.sort((a, b) => a -b)
// [1, 2, 3, 4, 5]

推理:

  1. 已知obj.method(a) 等价于obj.method.call(obj, a)
  2. 假设obj = arrmethod = sort
  3. 那么arr.sort(a)等价于arr.sort.call(arr, a)
  4. 假设a = (a, b) => a - b
  5. 那么arr.sort((a, b) => a - b)这就是一般的用法,它等价于arr.sort.call(arr, (a, b) => a - b)
  6. 因为arr.sort === Array.prototype.sort,那么var sort = Array.prototype.sort,得出sort.call(arr, (a, b) => a - b)

sort.call()的用法:接受一个数组和一个函数。对这个数组进行排序,排序的依据放在第二个参数。

map.callfilter.callreduce.call基本同理。