编辑代码

/*
 * @Descripttion:
 * @version:
 * @Author: wenlan
 * @Date: 2022-03-11 17:19:19
 * @LastEditors: wenlan
 * @LastEditTime: 2022-03-11 22:02:52
 */
/**
 * @name:
 * @test: test font
 * @msg:
 * @param {Object} thisArr 绑定的对象
 * @param {[]}  传入参数
 * @return {*}
 */

//edge case : fn already exist
// function call implemention
Function.prototype.mycall = function (thisArg, ...args) {
    // console.log(this); //隐式绑定
    //1获取需要被执行函数

    var fn = this;
    //fn(); //默认绑定
    //调用执行函数
    //边界情况 1 thisarr为数字类型需转换object
    // 2 call(null | undefined)传入为window
    //3 多参数 剩余参数
    thisArg = thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
    thisArg.fn = fn;
    var result = thisArg.fn(...args); //隐式调用
    delete thisArg.fn; //调用完删除 模拟call

    return result;
};

/**
 * @name:
 * @test: test font
 * @msg:
 * @param {Object} thisArg 绑定的对象
 * @param  { Array} arrArg 绑定的对象
 * @return {}
 */
Function.prototype.myapply = function (thisArg, arrArg) {
    var fn = this;
    thisArg = thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
    thisArg.fn = fn;
    //避免为传入参数 arrArg为undefined
    arrArg = arrArg || [];
    var result = thisArg.fn(...arrArg);
    delete thisArg.fn;
    return result;
};
//function bind implemention
Function.prototype.mybind = function (thisArg, ...arrArg) {
    var fn = this;
    thisArg = thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
    //
    function proxyFn(...finallArgs) {
        thisArg.fn = fn;
        var mergeArgs = [...arrArg, ...finallArgs];
        var result = thisArg.fn(mergeArgs);
        delete this.fn;
        return thisArg.fn;
    }
    //返回函数
    return proxyFn;
};
function foo(num1, num2, num3, num4) {
    console.log(num1, num2, num3, num4);
}
function sum(a, b) {
    return a + b;
}
//call
// foo.call();
// let result = sum.call({}, 10, 20);
// console.log("系统call调用结果", result);
// let res = sum.mycall({}, 12, 20);
// console.log("手写mycall调用结果:", res);

//apply
// let result = sum.apply({}, [10, 20]);
// console.log("系统apply调用结果", result);
// let res = sum.myapply("爱你", [12, 20]);
// foo.myapply("爱你");
// console.log("手写myapply调用结果:", res);

//bind
const bar = foo.mybind({},10, 20, 30, 40);
bar();