call、apply、bind
call
显式的设置 this
func.call(context, arg1, arg2, ...)apply
func.apply(context, args)args 是一个类数组对象
需要注意,arguments 正是一个 类数组。
呼叫转移(call forwarding):
js
let wrapper = function () {
return func.apply(this, arguments);
};apply 可能会更快,因为大多数 JavaScript 引擎在内部对其进行了优化。
bind
func.bind(context);bindAll
假设需要为一个对象的所有 Method 都 bind。
没有 bindAll 这样的 api,只能 for
js
for (let key in user) {
if (typeof user[key] == "function") {
user[key] = user[key].bind(user);
}
}也可以使用 lodash 的 .bindAll(object, methodNames)。
method borrowing / 方法借用
js
function hash() {
return [].join.call(arguments); // 1,2
}partial functions / 偏函数
js
function mul(a, b) {
return a * b;
}
// double 就是 偏函数
let double = mul.bind(null, 2);
double(3); // = mul(2, 3) = 6
double(4); // = mul(2, 4) = 8
double(5); // = mul(2, 5) = 10有时候,不想绑定 this ,只想绑定参数
js
function partial(func, ...argsBound) {
return function (...args) {
// this 取决于谁调用,也就没有bind。
return func.call(this, ...argsBound, ...args);
};
}