zoukankan      html  css  js  c++  java
  • 原生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;
    };
  • 相关阅读:
    java poi 从服务器下载模板写入数据再导出
    一个华为面试题
    ForEach 循环
    fmt标签格式化数字和时间
    Ichars制作数据统计图
    jQuery中的事件
    oracle学习第四天
    GET请求和POST请求
    Jsp的九个隐含对象
    Oracle学习【语句查询】
  • 原文地址:https://www.cnblogs.com/LeoXnote/p/13073920.html
Copyright © 2011-2022 走看看