手写简单call、apply、bind

1、call

        ~function(){
            function call_1(context, ...args){
                context = context == undefined ? window : context;
                let type = typeof context;
                if(!/^('object|function')$/.test(type)){
                    if(/^('bigint | symbol')$/.test(type)){
                        context = Object(context)
                    }else{
                        context = new context.constructor(context)
                    }
                }
                let key = Symbol('key');
                context[key] = this;
                let result = context[key](...args);
                delete context[key];
                return result;
            }
            Function.prototype.call_1 = call_1
        }()

2、apply

        ~function(){
            function apply_1(context, args){
                context = context == undefined ? window : context;
                Array.isArray(args)?args:[];
                let type = typeof context;
                if(!/^('object|function')$/.test(type)){
                    if(/^('bigint | symbol')$/.test(type)){
                        context = Object(context)
                    }else{
                        context = new context.constructor(context)
                    }
                }
                let key = Symbol('key');
                context[key] = this;
                let result = context[key](...args);
                delete context[key];
                return result;
            }
            Function.prototype.apply_1 = apply_1
        }()

3、bind

        ~function(){
            function bind_1(context, ...args){
                context = context == undefined ? window : context;
                Array.isArray(args)?args:[];
                let type = typeof context;
                if(!/^('object|function')$/.test(type)){
                    if(/^('bigint | symbol')$/.test(type)){
                        context = Object(context)
                    }else{
                        context = new context.constructor(context)
                    }
                }
                let _this = this
                return function(...innerArgs){
                    _this.call(context, ...args.concat(innerArgs)
                }
            }
            Function.prototype.bind_1 = bind_1
        }()

 

posted @ 2020-07-10 16:07  朝思暮想的虫  阅读(277)  评论(0编辑  收藏  举报