首页 > 移动平台 > 详细

手写简单call、apply、bind

时间:2020-07-10 16:57:31      阅读:60      评论:0      收藏:0      [点我收藏+]

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
        }()

 

手写简单call、apply、bind

原文:https://www.cnblogs.com/zmyxixihaha/p/13279750.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!