JavaScript深刻之bind的模拟实现

JavaScript深刻系列第十一篇,经过bind函数的模拟实现,带你们真正了解bind的特性git

bind

一句话介绍 bind:github

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

由此咱们能够首先得出 bind 函数的两个特色:闭包

  1. 返回一个函数
  2. 能够传入参数

返回函数的模拟实现

从第一个特色开始,咱们举个例子:app

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 () {
        self.apply(context);
    }

}复制代码

传参的模拟实现

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

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!post

这可咋办?不急,咱们用 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);
        self.apply(context, args.concat(bindArgs));
    }

}复制代码

构造函数效果的模拟实现

完成了这两点,最难的部分到啦!由于 bind 还有一个特色,就是this

一个绑定函数也能使用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 指向实例,self 指向绑定函数,由于下面一句 `fbound.prototype = this.prototype;`,已经修改了 fbound.prototype 为 绑定函数的 prototype,此时结果为 true,当结果为 true 的时候,this 指向实例。
        // 看成为普通函数时,this 指向 window,self 指向绑定函数,此时结果为 false,当结果为 false 的时候,this 指向绑定的 context。
        self.apply(this instanceof self ? 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);
        self.apply(this instanceof self ? 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 一样内容的英文版,就不存在这个判断!

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 () {
        self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
    }

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

    return fbound;

}复制代码

下一篇文章

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

相关连接

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

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

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

深刻系列

JavaScript深刻系列目录地址:github.com/mqyqingfeng…

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

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

相关文章
相关标签/搜索