亲宝软件园·资讯

展开

JS手写bind

前端西瓜哥 人气:0

大家好,我是前端西瓜哥,今天我们用 JS 来实现内置的 bind 方法。

bind 的用法

在实现之前,我们先学习一下 Function.prototype.bind 的用法。

function.bind(thisArg[, arg1[, arg2[, ...]]])

bind 是函数特有的一个方法,可以创建一个绑定了 this 的新函数。

接受的参数为如下。

this 的指向问题

我们在开发的时候,有时候会遇到 JS 的 this 指向丢失问题。

下面我们看一个例子。

const person = {
  nickname: '前端西瓜哥',
  eatWatermelon() {
    console.log(this.nickname + ' 吃西瓜');
  }
};

person.eatWatermelon();

上面的代码中,在调用 person.eatWatermelon 时,this 指向 person,输入结果为 前端西瓜哥 吃西瓜

下面我们再执行下面代码。

const eatWatermelon = person.eatWatermelon;
eatWatermelon();

输入结果就匪夷所思了起来,它是:undefined 吃西瓜

这是因为 this 的指向变成了 eatWatermelon() 执行时所在作用域的 this,在浏览器 script 标签最外层时,是全局对象 window(严格模式下,全局对象 this 会变成 undefined)。

所以  eatWatermelon()  执行中的 this.nickname 等价于 window.nickname,因为我们没有赋值过,所以是 undefined。

有时候我们不希望 this 丢失,该怎么办?

这时候我们就要用到一个 bind 方法,可以永久改变 this 的指向,且不能再改变。

const eatWatermelon = person.eatWatermelon.bind(person);
eatWatermelon();

这样的话,eatWatermelon 函数的 this 就会永远指向 person,能输出我们预期的 前端西瓜哥 吃西瓜

所以,对于一个函数来说,它的 this 指向是在执行时确定的

另一种控制 this 指向的写法是使用 箭头函数,尤其适合在函数中调用另一个函数的情况,因为篇幅原因这里不展开讲。

积累参数

bind 除了常用于强绑 this 外,另一个用的比较少的作用:预置函数参数。

function add(a, b, c) {
  return a + b + c;
}

const addSix = add.bind(null, 6);
const addSixThenAddFour = addSix.bind(null, 4);
addSixThenAddFour(5)
// 15

addSixThenAddFour(7)
// 17

实现一个 bind

下面进入正题,实现一个 bind。

Function.prototype.myBind = function(thisArg, ...prefixArgs) {
  const fn = this;
  return function(...args) {
    return fn.call(thisArg, ...prefixArgs, ...args);
  }
}

要点是利用 闭包

让返回的新函数可以访问到三个私有属性:

当我们调用这个新函数时,我们会执行 fn 函数,并利用 call 方法来指定 this 为 thisArg,然后将预填充的多个参数,和新函数接收的参数依次填入。

最后不要忘记返回调用后的值。因为新函数是原函数的封装,返回值也要和原函数表现一致。

结尾

bind 方法的实现并不复杂,更重要的是你要先掌握好 bind 的用法。

就好比做业务需求一样,不明确需求,就容易产生 bug,

然后需要你对闭包有一定的认识,知道如何去保存私有变量,以及封装函数的写法(记得 return 原函数的返回值)。

加载全部内容

相关教程
猜你喜欢
用户评论