call、apply、bind区别及其实现原理

307 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

call、apply、bind实现原理

区别:

call、apply、bind都是为了改变函数中的this指向。 call和apply的唯一区别就是方法传递的参数不同。 call/apply和bind的区别,call/apply是立即把函数执行,bind不是立即把函数执行,只是预先把this和后期需要传递的参数存储起来。

  • call用法
var callObj = { 0: 1111, 1: 2222, 2: 3333, length: 4 };
var param = [].slice.call(callObj);
param.forEach(item => { console.log(item) })
// =>1111 2222 3333
  • 实现原理
 Array.prototype.call =function myCall(context,...params){
    // context 要改变函数中的this指向context
    // 如果第一个参数为null让this使用window
    context == null ?context=window:null;
    // 如果要改变的this执行不是对象或函数 重新赋值一下
    if(!/^(function|object)$/.test(typeof context)) context = Object(context);
    // self 要执行的函数
    let self = this,
    // 确保唯一性
        key = Symbol['key'],
    // 执行返回结果
        result;
        context[key]=self;
    // 函数执行
        result = context[key](...params);
    delete context[key];
    return result;
}
  • apply实现原理
 Array.prototype.apply =function apply (context,...params){
    // context 要改变函数中的this指向context
    // 如果第一个参数为null让this使用window
    context == null ?context=window:null;
    // 如果要改变的this执行不是对象或函数 重新赋值一下
    if(!/^(function|object)$/.test(typeof context)) context = Object(context);
    // self 要执行的函数
    let self = this,
    // 确保唯一性
        key = Symbol['key'],
    // 执行返回结果
        result;
        context[key]=self;
    // 函数执行
        result = context[key](params);
    delete context[key];
    return result;
}
  • bind实现原理
function bind(context,...params){
   let self = this;
    return function proxy(...args){
        // 参数合并
        params = params.concat(args);
        return self.call(context,...params)
    }
}