js基础之call、apply、bind原理与实现

三者区别

  • apply、call、bind 三者都是函数的方法,第一个参数都是 this 要指向的对象,也就是想指定的上下文;html

  • apply、call、bind 三者均可以利用后续参数传参,其中只有apply()后续参数以数组形式传;segmentfault

  • bind 是返回对应的绑定函数,便于稍后调用;apply、call 则是当即调用数组

const parent = {
    age: 100,
    // 注意在用apply等时,这里不能用箭头函数,箭头定义时this已经指定,没法被apply等改变
    run: function(name) { console.log(this.age, name) }
};
const child = {
    age: 1
};

parent.run.apply(child, ["tom"]); // 1 tom // 当即执行
parent.run.call(child, "tom"); // 1 tom // 当即执行
parent.run.apply(null); // undefined undefined // null 是window下的,表示this指向window
parent.run.apply(undefined); // undefined undefined // undefined 指向window

const fn = parent.run.bind(child, "tom"); // bind会返回一个函数
fn(); // 1 tom
复制代码

原理 & 实现

call & apply

更详细能够参考JavaScript深刻之call和apply的模拟实现app

fn.apply(obj, array)实现的原理:函数

  • 将要执行的函数fn设置为该对象obj的属性
  • 执行obj.fn(args)函数
  • 不能给这个obj对象新增新的属性,因此要删除这个属性;
  • 其中对obj要作判断,为null或undefined时,要把this指向window
Function.prototype.call = function (context) {

    // 首先判断是否是函数调用该方法,若是不是,则抛出异常
    if (typeof this !== "function") throw new TypeError('Error');

    // 为**null或undefined**时,要把this指向window
    var context = context || window;

    // 将函数设置为obj的属性
    context.fn = this;

    // 类数组解构参数
    var args = [...arguments].slice(1);

    // 执行函数
    var result = context.fn(...args);

    // 删除函数
    delete context.fn;

    // 返回执行结果
    return result;
}

// apply与call不一样只在于参数处理不用
Function.prototype.apply = function (context, args) {

    // 首先判断是否是函数调用该方法,若是不是,则抛出异常
    if (typeof this !== "function") throw new TypeError('Error');

    // 为**null或undefined**时,要把this指向window
    var context = context || window;

    // 将函数设置为obj的属性
    context.fn = this;

    // 执行函数
    var result;
    if (args) {
        result = context.fn(...args);
    } else {
        result = context.fn();
    }

    // 删除函数
    delete context.fn;

    // 返回执行结果
    return result;
}
复制代码

bind

bind实际上是在call、apply基础上封装了一层,所以屡次调用bind,只会第一次生效;ui

parent.run.bind(child, "tom").bind(child1, "jack").bind(child2, "Rachael")();
// 1 tom 
// 并不会继续下去
复制代码

简单的实现:(实际要复杂一些)this

Function.prototype.myBind = function (context) {

    // 首先判断是否是函数调用该方法,若是不是,则抛出异常
    if (typeof this !== "function") throw new TypeError('Error');

    var me = this;

    // 去掉第一个函数参数
    var args = [...arguments].slice(1);
    // var args = Array.prototype.slice(arguments, 1);

    return function () {
        // 把后面的执行函数的参数拼接到bing参数后
        return me.apply(context, args.concat(...arguments);
        // return me.apply(context, args.concat(Array.prototype.slice(arguments));
    }
}
复制代码

首发于本人的博客:柴犬工做室spa

相关文章
相关标签/搜索