前言
背景
这两天在阅读 Koa.js 的源代码,在阅读过程中遇到了这样一段代码。
'use strict'
/**
* Expose compositor.
*/
module.exports = compose
/**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {Array} middleware
* @return {Function}
* @api public
*/
function compose (middleware) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function (context, next) {
// last called middleware #
let index = -1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(context, dispatch.bind(null, i + 1))); // 这里不明白
} catch (err) {
return Promise.reject(err)
}
}
}
}
这段代码大部分看起来都没什么问题,直到这句 return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
。里面的 dispatch.bind(null, i + 1)
不是很明白是什么意思。
环境
- Node.js: 14.x
目标
- 理解
Function.prototype.bind()
的用法
概述
bind()
方法创建一个新的函数,在bind()
被调用时,这个新函数的this
被指定为bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
也就是说,bind()
主要有两个作用。
- 将传入的第一个参数作为新函数的
this
- 其余参数作为新函数的参数
最后返回一个新的函数。
详细的参数和返回值的定义可以参考 MDN。
绑定 this
和其他语言不同,JavaScript 中函数的 this 在运行时是动态的,如果要确保 this 指向的是同一个对象,就可以使用 bind()
方法,第一个参数就是要绑定的 this。
this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX();
// 返回 9 - 因为函数是在全局作用域中调用的
// 创建一个新函数,把 'this' 绑定到 module 对象
// 新手可能会将全局变量 x 与 module 的属性 x 混淆
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81
Partially applied functions
中文翻译是偏函数,不知道为什么这么翻译。意思是可以配置 pre-specified initial arguments
,即预先指定的初始化参数。这个功能我之前是不知道的,直到看到了一开始遇到的那段代码。
function list() {
return Array.prototype.slice.call(arguments);
}
function addArguments(arg1, arg2) {
return arg1 + arg2
}
const list1 = list(1, 2, 3);
// [1, 2, 3]
const result1 = addArguments(1, 2);
// 3
// Create a function with a preset leading argument
const leadingThirtysevenList = list.bind(null, 37);
// Create a function with a preset first argument.
const addThirtySeven = addArguments.bind(null, 37);
const list2 = leadingThirtysevenList();
// [37]
const list3 = leadingThirtysevenList(1, 2, 3);
// [37, 1, 2, 3]
const result2 = addThirtySeven(5);
// 37 + 5 = 42
const result3 = addThirtySeven(5, 10);
// 37 + 5 = 42
// (the second argument is ignored)