原生實現call()、apply()、bind()

實現call()方法

Function.prototype.mycall = (context,...args) {
    // 判斷this是否函數,否返回typeerror
    if (typeof this !== 'function') {
        throw new TypeError('不是函數');
    }

    context = context || window;
    context.fn = this;

    const res = context.fn(...args);

    delete context.fn;
    return res; 
}

實現apply()

Function.prototype.myapply = (context,...args) => {
    if (typeof this !== 'function') {
        throw new TypeError('不是函數');
    }

    context = context || window;
    context.fn = this;
    args = args && args[0] || [];

    const res = context.fn(...args);

    delete context.fn;
    return res;
}

實現bind()

Function.prototype.mybind = (context,...args) => {
    if (typeof this !== 'function') {
        throw new TypeError('不是函數');
    }

    let fn = this;
    
    const bind = (...args2) => {
        return fn.apply(this instanceof bind?context:context,[...args,...args2]);
    }

    bind.prototype = Object.create(this.prototype);

    return bind;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章