前端手写

author: @linkaimin

Function.prototype.Call = function (context) {
    let cxt = context || window
    cxt.fn = this; 
    let args = [...arguments].slice(1) 
    let res = arguments.length > 1?cxt.fn(args):cxt.fn()
    delete cxt.fn 
    return res;
}
Function.prototype.Apply = function (context) {
    let cxt = context || window;
    cxt.fn = this;
    let args = [...arguments][1];
    res = arguments[1] ? cxt.fn(args):cxt.fn();
    delete cxt.fn;
    return res
}
Function.prototype.Bind = function (context) {
    if (typeof this !== 'function') {
        return;
    }
    let that = this;
    let args = [...arguments].slice(1);
    function fn() {
        let self = this instanceof that ? this : context;
        let addArgs = [...arguments];
        return that.apply(self, [...args, ...addArgs]);
    }
    fn.prototype = this.prototype;
    return fn;
}

最后更新于