【JS基础系列】bind方法的模拟实现

论坛 期权论坛 期权     
前端FE   2019-7-21 16:00   4366   0


01
前言

一句话介绍 bind:
bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )
由此我们可以首先得出 bind 函数的两个特点:
  • 返回一个函数
  • 可以传入参数

02
返回函数的模拟实现


从第一个特点开始,我们举个例子:
  1. var foo = {   
复制代码
  1.   value: 1
复制代码
  1. };
复制代码
  1. function bar() {   
复制代码
  1.     console.log(this.value);
复制代码
  1. }
复制代码
  1. // 返回了一个函数
复制代码
  1. var bindFoo = bar.bind(foo);
复制代码
  1. bindFoo(); // 1
复制代码
关于指定 this 的指向,我们可以使用 call 或者 apply 实现,关于 call 和 apply 的模拟实现,可以查看《JavaScript深入之call和apply的模拟实现》。我们来写第一版的代码:
  1. // 第一版
复制代码
  1. Function.prototype.bind2 = function (context) {
复制代码
  1.     var self = this;
复制代码
  1.     return function () {
复制代码
  1.         return self.apply(context);
复制代码
  1.     }
复制代码
  1. }
复制代码
此外,之所以
  1. return self.apply(context)
复制代码
,是考虑到绑定函数可能是有返回值的

03
传参的模拟实现


接下来看第二点,可以传入参数。这个就有点让人费解了,我在 bind 的时候,是否可以传参呢?我在执行 bind 返回的函数的时候,可不可以传参呢?让我们看个例子:
  1. var foo = {
复制代码
  1.     value: 1
复制代码
  1. };
复制代码
  1. function bar(name, age) {
复制代码
  1.     console.log(this.value);
复制代码
  1.     console.log(name);
复制代码
  1.     console.log(age);
复制代码
  1. [/code][code]}
复制代码
  1. var bindFoo = bar.bind(foo, 'daisy');
复制代码
  1. bindFoo('18');
复制代码
  1. // 1
复制代码
  1. // daisy
复制代码
  1. // 18
复制代码
函数需要传 name 和 age 两个参数,竟然还可以在 bind 的时候,只传一个 name,在执行返回的函数的时候,再传另一个参数 age!
这可咋办?不急,我们用 arguments 进行处理:
  1. // 第二版
复制代码
  1. Function.prototype.bind2 = function (context) {
复制代码
  1.     var self = this;
复制代码
  1.     // 获取bind2函数从第二个参数到最后一个参数
复制代码
  1.     var args = Array.prototype.slice.call(arguments, 1);
复制代码
  1.     return function () {
复制代码
  1.         // 这个时候的arguments是指bind返回的函数传入的参数
复制代码
  1.         var bindArgs = Array.prototype.slice.call(arguments);
复制代码
  1.         return self.apply(context, args.concat(bindArgs));
复制代码
  1.     }
复制代码
  1. }
复制代码

04
  1. 构造函数效果的模拟实现
复制代码


完成了这两点,最难的部分到啦!因为 bind 还有一个特点,就是
一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。
也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。举个例子:
  1. var value = 2;
复制代码
  1. [/code][code]var foo = {
复制代码
  1.     value: 1
复制代码
  1. };
复制代码
  1. [/code][code]function bar(name, age) {
复制代码
  1.     this.habit = 'shopping';
复制代码
  1.     console.log(this.value);
复制代码
  1.     console.log(name);
复制代码
  1.     console.log(age);
复制代码
  1. }
复制代码
  1. [/code][code]bar.prototype.friend = 'kevin';
复制代码
  1. [/code][code]var bindFoo = bar.bind(foo, 'daisy');
复制代码
  1. [/code][code]var obj = new bindFoo('18');
复制代码
  1. // undefined
复制代码
  1. // daisy
复制代码
  1. // 18
复制代码
  1. console.log(obj.habit);
复制代码
  1. console.log(obj.friend);
复制代码
  1. // shopping
复制代码
  1. // kevin
复制代码
注意:尽管在全局和 foo 中都声明了 value 值,最后依然返回了 undefind,说明绑定的 this 失效了,如果大家了解 new 的原理,就会知道这个时候的 this 已经指向了 obj。
所以我们可以通过修改返回的函数的原型来实现,让我们写一下:
  1. // 第三版
复制代码
  1. Function.prototype.bind2 = function (context) {
复制代码
  1.     var self = this;
复制代码
  1.     var args = Array.prototype.slice.call(arguments, 1);
复制代码
  1. [/code][code]    var fBound = function () {
复制代码
  1.         var bindArgs = Array.prototype.slice.call(arguments);
复制代码
  1.         // 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
复制代码
  1.         // 以上面的是 demo 为例,如果改成 `this instanceof fBound ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
复制代码
  1.         // 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
复制代码
  1.         return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
复制代码
  1.     }
复制代码
  1.     // 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
复制代码
  1.     fBound.prototype = this.prototype;
复制代码
  1.     return fBound;
复制代码
  1. }
复制代码
如果对原型链稍有困惑,可以查看《JavaScript深入之从原型到原型链》。

05
构造函数效果的优化实现


但是在这个写法中,我们直接将 fBound.prototype = this.prototype,我们直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype。这个时候,我们可以通过一个空函数来进行中转:
  1. // 第四版
复制代码
  1. Function.prototype.bind2 = function (context) {
复制代码
  1. [/code][code]    var self = this;
复制代码
  1.     var args = Array.prototype.slice.call(arguments, 1);
复制代码
  1. [/code][code]    var fNOP = function () {};
复制代码
  1. [/code][code]    var fBound = function () {
复制代码
  1.         var bindArgs = Array.prototype.slice.call(arguments);
复制代码
  1.         return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
复制代码
  1.     }
复制代码
  1. [/code][code]    fNOP.prototype = this.prototype;
复制代码
  1.     fBound.prototype = new fNOP();
复制代码
  1.     return fBound;
复制代码
  1. }
复制代码
到此为止,大的问题都已经解决,给自己一个赞!o( ̄▽ ̄)d

06
三个小问题


接下来处理些小问题:
1.apply 这段代码跟 MDN 上的稍有不同
在 MDN 中文版讲 bind 的模拟实现时,apply 这里的代码是:
  1. self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))
复制代码
多了一个关于 context 是否存在的判断,然而这个是错误的!
举个例子:
  1. var value = 2;
复制代码
  1. var foo = {
复制代码
  1.     value: 1,
复制代码
  1.     bar: bar.bind(null)
复制代码
  1. };
复制代码
  1. [/code][code]function bar() {
复制代码
  1.     console.log(this.value);
复制代码
  1. }
复制代码
  1. [/code][code]foo.bar() // 2
复制代码
以上代码正常情况下会打印 2,如果换成了 context || this,这段代码就会打印 1!
所以这里不应该进行 context 的判断,大家查看 MDN 同样内容的英文版,就不存在这个判断!
(2018年3月27日更新,中文版已经改了)
2.调用 bind 的不是函数咋办?
不行,我们要报错!
  1. if (typeof this !== "function") {
复制代码
  1.   throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
复制代码
  1. }
复制代码
3.我要在线上用
那别忘了做个兼容:
  1. Function.prototype.bind = Function.prototype.bind || function () {
复制代码
  1.     ……
复制代码
  1. };
复制代码
当然最好是用 es5-shim 啦。

07
最终代码


所以最后的代码就是:
  1. Function.prototype.bind2 = function (context) {
复制代码
  1.     if (typeof this !== "function") {
复制代码
  1.       throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
复制代码
  1.     }
复制代码
  1. [/code][code]    var self = this;
复制代码
  1.     var args = Array.prototype.slice.call(arguments, 1);
复制代码
  1. [/code][code]    var fNOP = function () {};
复制代码
  1. [/code][code]    var fBound = function () {
复制代码
  1.         var bindArgs = Array.prototype.slice.call(arguments);
复制代码
  1.         return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
复制代码
  1.     }
复制代码
  1. [/code][code]    fNOP.prototype = this.prototype;
复制代码
  1.     fBound.prototype = new fNOP();
复制代码
  1.     return fBound;
复制代码
  1. }
复制代码
感谢冴羽大佬的分享才有了这篇文章,建议反复阅读5遍以上,加深理解bind方法理解。

恭喜你,又掌握了一个新技能~

喜欢就点个关注吧~
关注微信公众号【前端FE】了解更多



「 往期精彩文章 」


vue项目-开启优化之旅
带你解析vue2.0的diff算法
【leetcode系列】001-两数之和





扫描二维码
获取更多精彩
前端FE



你点的每个好看,我都认真当成了喜欢
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:20
帖子:4
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP