手写call、apply、bind

342 阅读1分钟

撒也不说,直接上代码,skr....

// 手写call

Function.prototype.myCall = function(content) {
    if ('function' !== typeof this) {
        throw new TypeError('Error');
    }
    content = content || window;
    content.fn = this;
    const args = [...arguments].slice(1);
    const result = content.fn(...args);
    delete conten.fn;
    return result;
}

// 手写apply

ction.prototype.myApply = function(content) {
    if ('function' !== typeof this) {
        throw new TypeError('Error');
    }
    content = content || window;
    content.fn = this;
    let result;
    if (arguments[1]) {
        result = content.fn(...arguments[1]);
    } else {
        result = content.fn();
    }
    delete content.fn;
    return result;
}

// 手写bind

// bind返回的是一个函数,对于函数的调用方式有两种。一种是直接调用,一种是使用new;

Function.prototype.myBind = function(content) {
    if ('function' !== typeof this) {
        throw new TypeError('Error');
    }
    const _this = this;
    const args = arguments.slice(1);
    return function F() {
        if (this === F) {
            // function.bind(object, 1)(2)这样的调用方式,需要把参数拼接起来
            return new _this(...args, ...arguments);
        }
        return _this.apply(content, args.concat(...arguments));
    }
}