zoukankan      html  css  js  c++  java
  • ES6 spread operator 实现Function.prototype.apply

    之前出于好奇想自己实现apply的功能(不使用call,bind),一写才发现用eval无法实现,除非传入的参数全是字符串。

    今天突然看到这个ES6新特性spread opertor,发现有戏了

    Function.prototype.apply2 = function(obj, arg) {
      var t = typeof obj == 'object' && !!obj ? obj : window,
        res;
      t.__func__ = this;
      if(arg) {
        if(!Array.isArray(arg)) throw 'arg is not array';
        res = t.__func__(...arg);  //es6
      } else {
        res = t.__func__();
      }
      delete t.__func__;
      return res;
    };

    用eval是可以实现的

    Function.prototype.call2 = function(obj) {
      var t = typeof obj == 'object' && !!obj ? obj : window,
        args = Array.prototype.slice.call(arguments, 1),
        len = args.length,
        res;
      t.__func__ = this;
      if(len) {
        res = eval('t.__func__('+args.map(function(arg, index) {return ',args['+index+']'}).join('').substr(1)+')');
      } else {
        res = t.__func__();
      }
      delete t.__func__;
      return res;
    };
  • 相关阅读:
    python timeit模块用法
    boto3库限速
    golang-Beego-orm创建的坑
    Java07
    Java06
    Java04
    Java03
    c
    Mac 安装GCC
    命令: go build
  • 原文地址:https://www.cnblogs.com/coiorz/p/5158143.html
Copyright © 2011-2022 走看看