欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

向过去学习的 JavaScript - 绑定方法的实现

最编程 2024-05-01 08:55:06
...

bind()方法和apply()call()相似,都可以用来改变某个函数运行时this的指向。

并且同样接受的第一个参数作为它运行时的this,之后的参数都会传入作为它的参数。

但是bind()还有一个最大的特点就是它会创建一个新的函数,以便于我们稍后作调用,这也是它区别于apply()call()的地方。

先来看下bind的使用

var foo = {
    value: 1
};
function bar() {
    return this.value;
}
var bindFoo = bar.bind(foo);
console.log(bindFoo());     // 1

模拟实现一

Function.prototype.bind2 = function(context) {
    // 将this作保存,代表被绑定的函数
    var self = this;
    return function() {
        // 绑定函数可能会有返回值,所以这里要return一下
        return self.apply(context);
    }
}

bind的传参:需要注意我们在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, 'xiao');
bindFoo('18');
// 1
// xiao
// 18

传参效果的实现

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还有一个特点:就是 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

可以看到由于这里使用了new操作符,this已经指向了obj,因此this.value打印出来为undefined

构造函数效果的实现

为了让this指向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 指向 new 创建的实例,可以让实例获得来自绑定函数的值
        // 当作为普通函数时,将绑定函数的 this 指向 context
        return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
    }
    // 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
    fBound.prototype = this.prototype;
    return fBound;
}

不过上面的写法还存在点问题,fBound.prototype = this.prototype这一句代码直接修改了 fBound.prototype,也会直接修改绑定函数的 prototype。如下例子:

function bar() {}

var bindFoo = bar.bind2(null);

// 修改 bindFoo 的值
bindFoo.prototype.value = 1;

// 导致 bar.prototype 的值也被修改了
console.log(bar.prototype.value)    // 1

因此可以通过一个空函数作一个中转,避免绑定函数的 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;
}

当调用bind的不是函数还得做一下错误处理,完整实现如下:

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温故而知新——原型和原型链
  • JavaScript温故而知新——执行环境和作用域
  • JavaScript温故而知新——作用域链和闭包
  • JavaScript温故而知新——函数的4种调用方式
  • JavaScript温故而知新——call()和apply()的实现

推荐阅读