开发者社区> 问答> 正文

实现一个 call 或 apply

实现一个 call 或 apply

展开
收起
kun坤 2019-11-28 14:05:50 331 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
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Dynamic DDL Adding Structure to Streaming Data on the Fly 立即下载
Lambda Processing for Near Time Search Indexing 立即下载
Well-That-Escalated-Quickly-How-Abusing-The-Docker-API-Led-To-Remote-Code-Execution-Same-Origin-Bypass-And-Persistence 立即下载