call、bind、apply三者的用法和区别

call

call的理解:
call() 方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数

call方法的调用的整个过程:
当实例(函数)通过原型链的查找机制,找到function.prototype上的call方法,function call() {[ native code ]}

1、首先把药操作的函数中的this关键字变为call方法第一个传递的实参
2、把call方法第二个及之后的实参获取到
3、把药操作的函数执行,并且把第二个以后传递进来的实参传递给函数

然后面试中会经常问到自己怎么模拟手写一个call函数,以下是我看别人的博客总结的一些:
第一种:

Function.prototype.call2 = function(context) {
  const context = context || window
  context.fn = this
  let args = []
  for(let i = 1, len = arguments.length;i < len;i++) {
    args.push('arguments[' + i + ']')
  }
  const result = eval('context.fn(' + args +')')
  delete context.fn
  return result
}

第二种:

Function.prototype.myCall = function(context = window, ...args) {
  // context是指传入的red
  let func = this;
  let fn = Symbol("fn");
  context[fn] = func;

  let res = context[fn](...args);//重点代码,利用this指向,相当于context.caller(...args)
  // console.log('****',...args)
  delete context[fn];
  return res;
}
apply

apply的也是为了改变this的指向,但它和call的区别是传入的参数的不同

Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;

    var result;
    if (!arr) {
        result = context.fn();
    }
    else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }

    delete context.fn
    return result;
}

bind

bind( )方法创建一个新的函数,在bind( )被调用时,这个新函数的this被指定为bind()被调查时,这个新函数的this被指定为bind()的第一个参数,而其余参数作为新函数的参数,供调用时使用。

// 第四版
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值