javascript - 是否可以重写JavaScript的apply函数?

标签 javascript functional-programming overriding

为了掌握函数式编程的窍门,我重写了许多 JavaScript 的高阶函数,但我一直停留在 apply 上。是否可以用 JavaScript 编写 apply ?假设所有其他 native 函数都存在,并且正在使用 ES5 规范。

最佳答案

对于 ES5 及更低版本,我认为如果不使用 eval 就无法做到这一点(见下文)。您几乎可以通过args.length上的ma​​ssive switch语句来做到这一点,但在某些时候,您只需要说有一个限制该开关中的案例数量。

Function.prototype.newApply = function(thisArg, args) {
    switch (args.length) {
        case 0: return this.call(thisArg);
        case 1: return this.call(thisArg, args[0]);
        case 2: return this.call(thisArg, args[0], args[1]);
        // etc..
        default: throw new Error("She canna tek any more!");
    }
};

如果您允许eval,那么您绝对可以做到 - 完全归功于 blex建议评估:

Function.prototype.newApply = function(thisArg, args) {
    var f = this,
        call = "f.call(thisArg",
        i;
    for (i = 1; i < args.length; ++i) {
        call += ", args[" + i + "]";
    }
    call += ")";
    return eval(call);
};

实例:

Function.prototype.newApply = function(thisArg, args) {
  var f = this,
      call = "f.call(thisArg",
      i;
  for (i = 0; i < args.length; ++i) {
    call += ", args[" + i + "]";
  }
  call += ")";
  return eval(call);
};

var obj1 = {
  foo: "foo",
  bar: "bar"
};
var obj2 = {
  foo: "F",
  bar: "B"
};
function caps(o1, o2) {
  var k;
  snippet.log("this.x = " + this.x);
  for (k in o1) {
    o1[k] = o1[k].toUpperCase();
  }
  for (k in o2) {
    o2[k] = o2[k].toLowerCase();
  }
}

caps.newApply({x:42}, [obj1, obj2]);
snippet.log(JSON.stringify(obj1));
snippet.log(JSON.stringify(obj2));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

或者如果您想使用Array#reduce:

Function.prototype.newApply = function(thisArg, args) {
    var f = this,
        call = args.reduce(function(acc, _, index) {
            return acc + ", args[" + index + "]";
        }, "f.call(thisArg") + ")";
    return eval(call);
};
<小时/>

您在问题中提到了 ES5,但只是为了完整起见:由于扩展运算符 (...),在 ES6 中这真的很容易:

Function.prototype.newApply = function(thisArg, args) {
    return this.call(thisArg, ...args);
};

关于javascript - 是否可以重写JavaScript的apply函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051873/

相关文章:

javascript - 一个数组加上 arr.indexOf() 另一个数组的循环时间复杂度

javascript - android.app.RemoteServiceException : Context. startForegroundService() 之后没有在 React native 中调用 Service.startForeground()

javascript - 使用 Redux 的 store.getState() 和 store.dispatch() 进行更改而无需在 React 中订阅?

functional-programming - 有哪些令人印象深刻的函数式代码示例?

asp.net-mvc - ASP.NET MVC 4 移动显示模式停止工作

javascript - 在for循环javascript之外访问数组变量

collections - 将 int 列表折叠为 kotlin 中的范围列表

java - Scala 到 Java(函数式编程)

ios - Objective-C:覆盖 +initialize 和 +load 有用的情况

yocto - 添加 bbappend 条件任务而不覆盖配方功能