zoukankan      html  css  js  c++  java
  • 手写简单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
            }()
  • 相关阅读:
    结对第一次—疫情统计可视化(原型设计)
    软工实践寒假作业(2/2)
    软工实践寒假作业(1/2)
    Luogu P3975 [TJOI2015]弦论
    【模板】后缀自动机 (SAM)
    停用FF新鲜事/FF新推荐
    模板汇总
    Luogu P4467 [SCOI2007]k短路(模板)
    【模板】 最短路
    Luogu P5960 【模板】差分约束算法
  • 原文地址:https://www.cnblogs.com/zmyxixihaha/p/13279750.html
Copyright © 2011-2022 走看看