【问题标题】:How to create a function which packs function and arguments into an anonymous function [duplicate]如何创建一个将函数和参数打包成匿名函数的函数[重复]
【发布时间】:2014-09-21 06:22:35
【问题描述】:

使用此代码:

function printStuff(thing1, thing2) {
    console.log(thing1);
    console.log(thing2); 
  };

  function callWith(func, args) {
    return function () {
      func.apply(this, args);
    };
  }

  function callWith2() {
    theFunc = arguments[0];
    theArgs = arguments.slice(1);
    return function() {
      theFunc.apply(this, theArgs);
    };
  };

  x = callWith(printStuff, ["apples", "cheese"]);
  x();

  y = callWith2(printStuff, "apples", "cheese");
  y();

...为什么使用 callWith 有效,但使用 callWith2 会抛出错误?

有没有办法实现这个功能(即一个函数,它接受一个函数作为它的第一个参数和任意数量的其他参数(不是一个列表),并将这些参数输入到函数参数中以创建一个匿名的它返回的函数)?

【问题讨论】:

  • 嗯,你得到的错误信息'arguments.slice' is not a function不难理解?
  • 这不是我浏览器中的错误信息,而是:“Uncaught TypeError: undefined is not a function”
  • 道歉。但是,我不理解愤怒。
  • 很抱歉,如果出现错误。
  • 投反对票的人能解释原因吗?我看不出我应该如何从没有收到行号的神秘错误消息中看出(“Uncaught TypeError:undefined is not a function”)试图对参数对象进行切片是问题所在,因此不是直到发布与声称是副本的问题有任何关系的问题之后才明显。我应该在问问题之前就知道答案吗?

标签: javascript


【解决方案1】:

arguments 不是一个真正的数组,而是一个带有数字键的对象,一个伪数组。您需要通过调用数组的slice 方法将其转换为真实数组以对其进行切片,并将参数作为上下文:

theArgs = [].slice.call(arguments, 1)

您可能想要创建一个toArray 助手:

var toArray = Array.call.bind([].slice)

现在你可以这样做了:

theArgs = toArray(arguments).slice(1)

【讨论】:

  • 啊!谢谢你。这比我担心的答案要简单得多。
猜你喜欢
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多