• 原生js手动实现apply和call


    // call模拟
    Function.prototype.call_ = function (obj) {
        //判断是否为null或者undefined,同时考虑传递参数不是对象情况
        obj = obj ? Object(obj) : window;
        var args = [];
        // 注意i从1开始
        for (var i = 1, len = arguments.length; i < len; i++) {
            args.push("arguments[" + i + "]");
        };
        obj.fn = this; // 此时this就是函数fn
        var result = eval("obj.fn(" + args + ")"); // 执行fn
        delete obj.fn; //删除fn
        return result;
    };
    // apply模拟
    Function.prototype.apply_ = function (obj, arr) {
        obj = obj ? Object(obj) : window;
        obj.fn = this;
        var result;
        if (!arr) {
            result = obj.fn();
        } else {
            var args = [];
            // 注意这里的i从0开始
            for (var i = 0, len = arr.length; i < len; i++) {
                args.push("arr[" + i + "]");
            };
            result = eval("obj.fn(" + args + ")"); // 执行fn
        };
        delete obj.fn; //删除fn
        return result;
    };

    ES6实现

    // ES6 call
    Function.prototype.call_ = function (obj) {
        obj = obj ? Object(obj) : window;
        obj.fn = this;
        // 利用拓展运算符直接将arguments转为数组
        let args = [...arguments].slice(1);
        let result = obj.fn(...args);
    
        delete obj.fn
        return result;
    };
    // ES6 apply
    Function.prototype.apply_ = function (obj, arr) {
        obj = obj ? Object(obj) : window;
        obj.fn = this;
        let result;
        if (!arr) {
            result = obj.fn();
        } else {
            result = obj.fn(...arr);
        };
    
        delete obj.fn
        return result;
    };
  • 相关阅读:
    POJ 1731
    POJ 1256
    POJ:1833 按字典序找到下一个排列:
    git工作流
    git 分之合并和冲突解决
    iis 7 操作 .net
    IIS7.0 Appcmd 命令详解
    SQL的注入式攻击方式和避免方法
    实例详解Django的 select_related
    django-ajax之post方式
  • 原文地址:https://www.cnblogs.com/LeoXnote/p/13073920.html
Copyright © 2020-2023  润新知