call-apply-bind

174 阅读1分钟

call

  • call
    • 改变this指向
    • 让函数执行
function fn1() {
    console.log(this);
}

function fn2() {
    console.log(100);
}

Function.prototype.call = function(context, ...args) {
    context = context ? Object(context) : global;
    // 这里的this就是Function.prototype。即传入的方法体对象
    context.fn = this; //call的特点就是将自己放到一个对象上(fn),通过对象调用
    let result = context.fn(...args);
    delete context.fn;
    return result;
}

fn1.call(1);

// demo1
fn1.call.call.call.call.call(fn2); //100 //等价于 fn1.call();

apply

  • apply
    • 参考call实现,参数传递不再是剩余参数,是数组
Function.prototype.apply = function(context, arrArgs) {
    context = context ? Object(context) : global;
    context.fn = this; //call的特点就是将自己放到一个对象上(fn),通过对象调用
    let result = context.fn(...arrArgs);
    delete context.fn;
    return result;
}

function fn3(a, b) {
    console.log(this, a, b);
}

fn3.apply(1, [2, 3]);

bind

  • bind
    • 只绑定this,返回一个函数
Function.prototype.bind = function(context) {
    let self = this;
    return function(...args) {
        return self.call(context, ...args);
    }
}

function fn4(a, b) {
    console.log(this, a, b);
}

fn4.bind(1)(2, 3);

// 多次bind,只看第一次绑定的上下文
function fn5() {
    console.log(this);
}
fn5.bind(1).bind(2)(); //[Number: 1]