js apply、call、bind实现

118 阅读1分钟

本文实现了apply、call和bind,无论apply、call还是bind都是绑定this,apply和call的区别只是一个传数组,一个传多个值,而bind返回一个绑定this的函数。

一、apply

Function.prototype.apply = function (ctx, args) {
    ctx = ctx || window
    const fn = Symbol();
    ctx[fn] = this;
    const result = ctx[fn](...args);
    delete ctx.fn;
    return result;
}

二、call

Function.prototype.call = function (ctx, ...args) {
    ctx = ctx || window;
    const fn = Symbol();
    ctx[fn] = this;
    const result = ctx[fn](...args);
    delete ctx[fn];
    return result;
}

三、bind

Function.prototype.bind = function (ctx, ...args) {
    ctx = ctx || window;
    const fn = Symbol();
    ctx[fn] = this;
    
    function _fn() {
        if (this instanceof _fn) {
            return new ctx[fn](...args);
        } else {
            const result = ctx[fn](...args);
            return result;
        }
    }
    
    _fn.prototype = this.prototype;
    
    return _fn;
}