Blog icon indicating copy to clipboard operation
Blog copied to clipboard

JavaScript深入之bind的模拟实现

Open mqyqingfeng opened this issue 7 years ago • 200 comments

bind

一句话介绍 bind:

bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )

由此我们可以首先得出 bind 函数的两个特点:

  1. 返回一个函数
  2. 可以传入参数

返回函数的模拟实现

从第一个特点开始,我们举个例子:

var foo = {
    value: 1
};

function bar() {
    console.log(this.value);
}

// 返回了一个函数
var bindFoo = bar.bind(foo); 

bindFoo(); // 1

关于指定 this 的指向,我们可以使用 call 或者 apply 实现,关于 call 和 apply 的模拟实现,可以查看《JavaScript深入之call和apply的模拟实现》。我们来写第一版的代码:

// 第一版
Function.prototype.bind2 = function (context) {
    var self = this;
    return function () {
        return self.apply(context);
    }

}

此外,之所以 return self.apply(context),是考虑到绑定函数可能是有返回值的,依然是这个例子:

var foo = {
    value: 1
};

function bar() {
	return this.value;
}

var bindFoo = bar.bind(foo);

console.log(bindFoo()); // 1

传参的模拟实现

接下来看第二点,可以传入参数。这个就有点让人费解了,我在 bind 的时候,是否可以传参呢?我在执行 bind 返回的函数的时候,可不可以传参呢?让我们看个例子:

var foo = {
    value: 1
};

function bar(name, age) {
    console.log(this.value);
    console.log(name);
    console.log(age);

}

var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18

函数需要传 name 和 age 两个参数,竟然还可以在 bind 的时候,只传一个 name,在执行返回的函数的时候,再传另一个参数 age!

这可咋办?不急,我们用 arguments 进行处理:

// 第二版
Function.prototype.bind2 = function (context) {

    var self = this;
    // 获取bind2函数从第二个参数到最后一个参数
    var args = Array.prototype.slice.call(arguments, 1);

    return function () {
        // 这个时候的arguments是指bind返回的函数传入的参数
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(context, args.concat(bindArgs));
    }

}

构造函数效果的模拟实现

完成了这两点,最难的部分到啦!因为 bind 还有一个特点,就是

一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。举个例子:

var value = 2;

var foo = {
    value: 1
};

function bar(name, age) {
    this.habit = 'shopping';
    console.log(this.value);
    console.log(name);
    console.log(age);
}

bar.prototype.friend = 'kevin';

var bindFoo = bar.bind(foo, 'daisy');

var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin

注意:尽管在全局和 foo 中都声明了 value 值,最后依然返回了 undefind,说明绑定的 this 失效了,如果大家了解 new 的模拟实现,就会知道这个时候的 this 已经指向了 obj。

(哈哈,我这是为我的下一篇文章《JavaScript深入系列之new的模拟实现》打广告)。

所以我们可以通过修改返回的函数的原型来实现,让我们写一下:

// 第三版
Function.prototype.bind2 = function (context) {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        // 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
        // 以上面的是 demo 为例,如果改成 `this instanceof fBound ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
        // 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
        return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
    }
    // 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
    fBound.prototype = this.prototype;
    return fBound;
}

如果对原型链稍有困惑,可以查看《JavaScript深入之从原型到原型链》

构造函数效果的优化实现

但是在这个写法中,我们直接将 fBound.prototype = this.prototype,我们直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype。这个时候,我们可以通过一个空函数来进行中转:

// 第四版
Function.prototype.bind2 = function (context) {

    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}

到此为止,大的问题都已经解决,给自己一个赞!o( ̄▽ ̄)d

三个小问题

接下来处理些小问题:

1.apply 这段代码跟 MDN 上的稍有不同

在 MDN 中文版讲 bind 的模拟实现时,apply 这里的代码是:


self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))

多了一个关于 context 是否存在的判断,然而这个是错误的!

举个例子:

var value = 2;
var foo = {
    value: 1,
    bar: bar.bind(null)
};

function bar() {
    console.log(this.value);
}

foo.bar() // 2

以上代码正常情况下会打印 2,如果换成了 context || this,这段代码就会打印 1!

所以这里不应该进行 context 的判断,大家查看 MDN 同样内容的英文版,就不存在这个判断!

(2018年3月27日更新,中文版已经改了😀)

2.调用 bind 的不是函数咋办?

不行,我们要报错!

if (typeof this !== "function") {
  throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}

3.我要在线上用

那别忘了做个兼容:

Function.prototype.bind = Function.prototype.bind || function () {
    ……
};

当然最好是用 es5-shim 啦。

最终代码

所以最最后的代码就是:

Function.prototype.bind2 = function (context) {

    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}

下一篇文章

《JavaScript深入系列之new的模拟实现》

相关链接

《JavaScript深入之从原型到原型链》

《JavaScript深入之call和apply的模拟实现》

《JavaScript深入系列之new的模拟实现》

深入系列

JavaScript深入系列目录地址:https://github.com/mqyqingfeng/Blog

JavaScript深入系列预计写十五篇左右,旨在帮大家捋顺JavaScript底层知识,重点讲解如原型、作用域、执行上下文、变量对象、this、闭包、按值传递、call、apply、bind、new、继承等难点概念。

如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎star,对作者也是一种鼓励。

mqyqingfeng avatar May 03 '17 02:05 mqyqingfeng

先来个沙发,等会有时间看

jawil avatar May 03 '17 02:05 jawil

哈哈,欢迎光临。@jawil

mqyqingfeng avatar May 03 '17 02:05 mqyqingfeng

前辈,好像有一个typo。 模拟构造函数效果里的代码,有一个hobbit-霍比特人属性,应该是habit-习惯吧?#笑哭

JuniorTour avatar May 06 '17 12:05 JuniorTour

哈哈,确实是写错了,本来是想写habit,没有想到hobbit写的太顺手,我竟然没有任何违和的感觉……感谢指出哈~

mqyqingfeng avatar May 08 '17 02:05 mqyqingfeng

我把最后的实现代码跑了一下构造函数的例子 发现this依然失效了啊 是什么问题呢

enjkvbej avatar May 22 '17 03:05 enjkvbej

@enjkvbej 作为构造函数时,this 就是会失效呐

mqyqingfeng avatar May 22 '17 03:05 mqyqingfeng

😄

jawil avatar May 22 '17 03:05 jawil

@jawil 说起来,博主的 V8 源码系列写得怎么样了?很好奇第一篇会讲什么?

mqyqingfeng avatar May 22 '17 03:05 mqyqingfeng

V8 源码系列从入门到放弃,卒

jawil avatar May 22 '17 04:05 jawil

fNOP.prototype = this.prototype; fbound.prototype = new fNOP();

是不是就等于fbound.prototype = Object.create(this.prototype);

fbsstar avatar May 27 '17 01:05 fbsstar

@fbsstar 是的,Object.create 的模拟实现就是:

Object.create = function( o ) {
    function f(){}
    f.prototype = o;
    return new f;
};

mqyqingfeng avatar May 27 '17 02:05 mqyqingfeng

对第三版模拟实现代码进行了优化。以前是

this instanceof self ? this : context

现在改成了

this instanceof fBound ? this : context

因为 fNOP.prototype = this.prototype的缘故,两段代码在效果上并没有区别,但是个人觉得改成 fBound 会更好理解, 而且 MDN 也是采用的 fBound 。

mqyqingfeng avatar Jun 15 '17 07:06 mqyqingfeng

为什么要设置 fBound.prototype = this.prototype,只是为了继承一下绑定函数的原型对象中的属性吗?

caiyongmin avatar Jun 20 '17 13:06 caiyongmin

@caiyongmin 为了让 fBound 构造的实例能够继承绑定函数的原型中的值

mqyqingfeng avatar Jun 21 '17 02:06 mqyqingfeng

我的意思是,为什么要继承?

caiyongmin avatar Jun 21 '17 13:06 caiyongmin

@caiyongmin 因为原生的 bind 的效果就是这样呐

mqyqingfeng avatar Jun 21 '17 15:06 mqyqingfeng

您好,我们直接将 fBound.prototype = this.prototype,我们直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype。这里有点不太懂诶,能多讲解一下吗,谢谢

liuxinqiong avatar Jun 29 '17 02:06 liuxinqiong

@liuxinqiong 我们来写个 demo 哈:

Function.prototype.bind2 = function (context) {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
    }
    fBound.prototype = this.prototype;
    return fBound;
}


function bar() {}

var bindFoo = bar.bind2(null);

bindFoo.prototype.value = 1;

console.log(bar.prototype.value) // 1

你会发现我们明明修改的是 bindFoo.prototype ,但是 bar.prototype 的值也被修改了,这就是因为 fBound.prototype = this.prototype导致的。

mqyqingfeng avatar Jun 29 '17 03:06 mqyqingfeng

@mqyqingfeng 万分感谢,点破之后,对之前的知识都有了新的认识!已经第二次看了,每次都有收获!

liuxinqiong avatar Jun 29 '17 03:06 liuxinqiong

@liuxinqiong 哈哈,感谢肯定~ 加油哈~

mqyqingfeng avatar Jun 29 '17 03:06 mqyqingfeng

建议第三版中 fBound.prototype = this.prototype; 修改为: fBound.prototype = self.prototype; 因为构造函数版本中,个人认为 核心是两个this的理解,如果理解了两个this,那么基本上就没太大的坑了。 再者用es6语法 写demo可读性更强

youzaiyouzai666 avatar Jul 12 '17 08:07 youzaiyouzai666

@youzaiyouzai666 感谢指出,改成 self 能避免理解混乱,确实更好一些~ 关于 es6 的写法,我给自己的要求是在没写 ES6 系列之前,尽量保持 ES5 的写法,这是希望看这个系列的初学者们不要有额外的学习成本

mqyqingfeng avatar Jul 13 '17 04:07 mqyqingfeng

看到写bind最少的代码

// The .bind method from Prototype.js
Function.prototype.bind = function(){
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
  return function(){
    return fn.apply(object,
      args.concat(Array.prototype.slice.call(arguments)));
  };
};

分享一下

baixiaoji avatar Aug 18 '17 02:08 baixiaoji

@baixiaoji 感谢分享哈~

不过这段代码并没有完整的实现 bind 的特性,比如 "当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效"

var value = 2;

var foo = {
    value: 1
};

function bar(name, age) {
    console.log(this.value);
}

var bindFoo = bar.bind(foo);

var obj = new bindFoo('18');

使用原生的 bind 就会返回 undefined,使用这段代码的话,就会返回 1

mqyqingfeng avatar Aug 18 '17 03:08 mqyqingfeng

最终版代码应该是

  this instanceof fBound

而不是

  this instanceof fNOP

stickmy avatar Aug 19 '17 11:08 stickmy

有个疑惑,最终代码中不需要将 fBound 的 constructor 给指回来吗?

fBound.prototype = new fNOP();

即:

fBound.prototype.constructor = fBound;

cobish avatar Aug 21 '17 07:08 cobish

@Bloss 因为 fBound.prototype = new fNOP() 的缘故,两种写法实现的效果是一致的~

mqyqingfeng avatar Aug 22 '17 02:08 mqyqingfeng

@mqyqingfeng 是这样的= =,谢谢博主

stickmy avatar Aug 22 '17 02:08 stickmy

@cobish 并不需要哈~ 我们先看下原生的 bind() 方法的特性:

bind 方法所返回的函数并不包含 prototype 属性,并且将这些绑定的函数用作构造函数所创建的对象从原始的未绑定的构造函数中继承 prototype

这就意味着如果你打印构造函数所创建的对象的 constructor 属性,应该指向未绑定的构造函数,举个例子:

    var foo = { value: 1};
    function bar() {}
    var bindFoo = bar.bind(foo);
    var obj = new bindFoo();
    console.log(obj.constructor);

原生会打印 bar 函数,如果 fBound.prototype.constructor = fBound 的话,就变成了打印 fBound 函数,如果没有这句话,因为 fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); 的缘故,就会指向 bar 函数

mqyqingfeng avatar Aug 22 '17 02:08 mqyqingfeng

@mqyqingfeng 谢谢解惑,万分感谢~

cobish avatar Aug 24 '17 07:08 cobish