bind、call、apply 的区别,手写 bind
参考答案
区别
call(thisArg, a, b):立即调用,参数逐个传;apply(thisArg, [a, b]):立即调用,参数用数组/类数组;bind(thisArg, ...args):不调用,返回永久绑定 this 与新函数(可预设参数,支持 new)。
手写 bind
Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
function Bound(...args) {
// new 调用时 this 指向新实例,忽略绑定的 ctx
return this instanceof Bound
? Reflect.construct(fn, [...preset, ...args])
: fn.apply(ctx, [...preset, ...args]);
}
Bound.prototype = Object.create(fn.prototype || null);
return Bound;
};
要点:预设参数合并、new 优先级高于 bind、保留 prototype、长度/名称可忽略。
(实际可用箭头函数 + 闭包简化,但那样不支持 new。)