• bind call apply 的原理


    !function (proto) {
        function getContext(context) {
            context = context || window;
            var type = typeof context;
            if (['number', 'string', 'boolean', 'null'].includes(type)) {
                context = new context.constructor(context);
            }
            return context;
        }
        function call(context, ...args) {
            context = getContext(context);
            context._fn = this;
            let result = context._fn(...args);
            delete context._fn;
            return result;
        }
        function apply(context, args) {
            context = getContext(context);
            context._fn = this;
            let result = context._fn(...args);
            delete context._fn;
            return result;
        }

        function bind(context, ...bindArgs) {
            //  this = getName
            return (...args) => this.call(context, ...bindArgs, ...args);
        }
        proto.call = call;
        proto.apply = apply;
        proto.bind = bind;
    }(Function.prototype)
    function getName(age, home){
        console.log(this.name, age, home);
    }
    let obj = {name: 'xiao'}
    // getName.call(obj, 10, 'gzhou')



    // getName.apply(obj, [11, 'shenzhen'])


    let bindFn = getName.bind(obj, 10)
    bindFn('北京')
    越努力越幸运
  • 相关阅读:
    Java知识15 Number&Math类【多测师】
    python callable()方法实例
    高级super实例
    高级any、for组合用法
    python 字典update、setdefault、pop方法案例
    一个经典的python字典生成式案例
    一个发挥到极致的yield案例
    python map使用
    Python yield详解
    django __path__使用
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/14514813.html
Copyright © 2020-2023  润新知