apply,call,bind方法简单实现

apply方法:在传入的this对象中创建函数,以实现在this环境中执行函数的功能。

let func1 = {
    name: 'test'
}
let func2 = function (a, b, c) {
    return a + b + c + this.name;
}

Function.prototype.myApply = function (thisArg, argArr) {
    thisArg = thisArg ? Object(thisArg) : window;
    thisArg.func = this;
    let result = thisArg.func(...argArr);
    delete thisArg.func;
    return result;
}

func2.myApply(func1, ['1', '2', '3']);       //123test

call方法:同上,参数传入方式不同。

let func1 = {
    name: 'test'
}
let func2 = function (a, b, c) {
    return a + b + c + this.name;
}

Function.prototype.myCall = function (thisArg, ...argArr) {
    thisArg = thisArg ? Object(thisArg) : window;
    thisArg.func = this;
    let result = thisArg.func(...argArr);
    delete thisArg.func;
    return result;
}

func2.myCall(func1, '1', '2', '3');       //123test

bind方法:返回的是一个函数,而不是运行结果,并且注意继承和实例问题。

let func1 = {
    name: 'test'
}
let func2 = function (a, b, c) {
    return a + b + c + this.name;
}

Function.prototype.myBind = function (thisArg, ...argArr) {
    let self = this;

    let Bound = function (...args) {
        //如果当前为bound的实例,直接使用bound的this
        let thisAgr = this instanceof Bound ? this : self;

        return self.apply(thisAgr, [...argArr, ...args]);
    }

    //为了可以找到目标函数,即func2的原型中的属性和方法,继承当前函数的原型链方法
    Bound.prototype = Object.create(self.prototype);
    Bound.prototype.constructor = self;

    return bound;
}

func2.myBind(func1, '1', '2', '3')();       //123test    
原文地址:https://www.cnblogs.com/xiaokeai0110/p/14045267.html