手写call apply bind

Function.prototype.myCall = function (context, ...args) {
    if (typeof this !== 'function') {
        throw new TypeError('error');
    }

    context.fn = this;

    let res = context.fn(...args);
    delete context.fn;
    return res;
}


Function.prototype.myApply = function (context, arr) {
    if (!Array.isArray(arr)) {
        throw new TypeError(' the second parameter must be an Array');
    }

    context.fn = this;
    let res = context.fn(...arr);
    delete context.fn;
    return res;

}



Function.prototype.myBind = function (context,...args) {
    if(typeof this !== 'function'){
        throw new TypeError('Error');
    }
    let self = this;
    return function F(){
        if(this instanceof F){
            return new self(...args,...arguments);
        }
        return self.call(context,[...args,...arguments]);
    }
}

 

posted @ 2021-09-28 16:49  龚小航  阅读(31)  评论(0)    收藏  举报