bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

需要注意的点有,

  1. 挂载到 Function 的原型上
  2. 具有 thisArgs 和 原函数所需的其他参数
  3. thisArgs 传递的任何值都需转换为对象
  4. bind 中输入的原函数所需的参数需要在返回函数中能接上,意思就是下面两种方式都要支持
js
foo.bind(obj,1,2)(3) foo.bind(obj,1,2,3)
  1. 返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
js
Function.prototype.myBind = function (thisArgs, ...args1) { thisArgs = Object(thisArgs) const _self = this; // const args1 = Array.prototype.slice.call(arguments, 1); return function (...args2) { // const args2 = Array.prototype.slice.call(arguments, 1); return _self.apply(thisArgs, args1.concat(args2)); }; };
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:叶继伟

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!