zoukankan      html  css  js  c++  java
  • 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('北京')
    越努力越幸运
  • 相关阅读:
    AJax 源码思路
    C语言博客作业--字符数组
    C语言博客作业--一二维数组
    C语言博客作业--数据类型
    C语言博客作业--函数
    C语言博客作业--嵌套循环
    C语言第三次博客作业---单层循环结构
    C语言第二次博客作业---分支结构
    C语言第一次博客作业——输入输出格式
    C语言博客作业--数据类型
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/14514813.html
Copyright © 2011-2022 走看看