开发者社区> 问答> 正文

实现一个 call 或 apply

实现一个 call 或 apply

展开
收起
kun坤 2019-11-28 14:05:50 326 0
1 条回答
写回答
取消 提交回答
  • call
    
    Function.prototype.call2 = function(context) {
      var context = context || window;
      context.fn = this;
    
      var args = [];
      for (var i = 1, len = arguments.length; i < len; i++) {
        args.push("arguments[" + i + "]");
      }
    
      var result = eval("context.fn(" + args + ")");
    
      delete context.fn;
      return result;
    };
    
    apply
    
    Function.prototype.apply2 = function(context, arr) {
      var context = Object(context) || window;
      context.fn = this;
    
      var result;
      if (!arr) {
        result = context.fn();
      } else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
          args.push("arr[" + i + "]");
        }
        result = eval("context.fn(" + args + ")");
      }
    
      delete context.fn;
      return result;
    };
        ```
    2019-11-28 14:06:06
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Froma single droplet toafull b 立即下载
The-Future-Of-Applepwn-How-To-Save-Your-Money 立即下载
低代码开发师(初级)实战教程 立即下载