跳到主要内容

bind

2024年03月12日
柏拉文
越努力,越幸运

一、认识


Function.prototype.bind() 创建一个新函数,当调用该新函数时,它会调用原始函数并将其 this 关键字设置为给定的值,同时,还可以传入一系列指定的参数,这些参数会插入到调用新函数时传入的参数的前面。

二、语法


bind(thisArg); // 相当于 func();
bind(thisArg, arg1); // 相当于 func(arg1);
bind(thisArg, arg1, arg2); // 相当于 func(arg1, arg2);
bind(thisArg, arg1, arg2, /* …, */ argN); // 相当于 func(arg1, arg2, ……, argN);

const bindFunc = bind(thisArg, arg1);
bindFunc(arg2,arg3); // 相当于 func(arg1, arg2, arg3)。 bind 可以进行参数拼接
  • thisArg: 在调用绑定函数时,作为 this 参数传入目标函数 func 的值。如果函数不在严格模式下,nullundefined 会被替换为全局对象,并且原始值会被转换为对象。如果使用 new 运算符构造绑定函数,则忽略该值。

  • arg1, …, argN: 在调用 func 时,插入到传入绑定函数的参数前的参数。

  • 返回值: 使用指定的 this 值和初始参数(如果提供)创建的给定函数的副本。

三、应用场景


3.1 预置参数

描述: 在具体上下文中, 将某些数据先预先传入, 后续调用或者传入其他参数。

function dispatchAction(data, index){
……
}

function foo(){
const data = []; // 重要数据
const dispatch = dispatchAction.bind(null, data);
}

// 后续调用时, 只需传入 index 即可
dispatch(0);

四、实现原理


4.1 实现

Function.prototype.bind = function (thisArg, ...argArrayOut) {
const fn = this;

if (thisArg) {
thisArg = Object(thisArg);
} else {
thisArg = typeof window === "undefined" ? global : window;
}

return function (...argArrayIn) {
thisArg.__fn__ = fn;
const finalArgus = [...argArrayOut, ...argArrayIn];
const result = thisArg.__fn__(...finalArgus);
delete thisArg.__fn__;
return result;
};
};

4.2 测试

function foo(name, age, ...args) {
console.log(this);
console.log(name, age);
console.log(args);
}
const obj = {
name: "柏拉图",
age: 23,
};
const fooBind = foo.bind(obj, "哈哈哈", 32);
fooBind("嘻嘻嘻", 250);