【问题标题】:Can't get `arguments` of inner arrow function无法获取内部箭头函数的“参数”
【发布时间】:2018-01-26 19:14:14
【问题描述】:

当我意识到它没有按预期工作时,我正在制作一个装饰器函数来响应this question。该函数只是计算给定函数被调用的次数,并记录下来。

function countExecutions(fn) {
    let count = 0;
    return () => {
        console.log("called",++count);
        return fn.apply(this, arguments);;
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // (a,b) => a+bundefined

我意识到这是因为arguments 引用了函数countExecutions 的参数,而不是我的内部匿名函数。 所以它记录了(a,b) => a+bundefined 而不是3为什么我不能获取内部匿名函数的参数?

如果我给它一个名字,它会按预期工作:

function countExecutions(fn) {
    let count = 0;
    return function inner() {
        console.log("called",++count);
        return fn.apply(this, arguments);;
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // 3

【问题讨论】:

  • 箭头函数没有thisarguments
  • 应该也可以不命名它 - 只是做一个正常的function() {}
  • 哦,对了!!所以这不是匿名,只是箭头
  • @jhpratt:我的问题与那个问题很接近,但我得到了更多有用的答案。所以我不想将其标记为重复。谢谢!

标签: javascript


【解决方案1】:

我认为你误解了箭头函数,这是你的匿名(不使用箭头函数)版本:

(或者,您可以使用@trincot's answer 中所述的箭头函数。)

function countExecutions(fn) {
    let count = 0;
    return function(){
        console.log("called",++count);
        return fn.apply(this, arguments);;
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // (a,b) => a+bundefined

【讨论】:

  • 您能否添加 @trincot 的替代方案来完成您的答案?对于将来的类似问题会很好。
【解决方案2】:

如上所述,arguments 没有为箭头函数定义。但是为什么不使用扩展语法:

function countExecutions(fn) {
    let count = 0;
    return (...args) => {
        console.log("called",++count);
        return fn.apply(this, args);
    }
}

var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // 3

【讨论】:

    【解决方案3】:

    由于函数被命名,它不会以这种方式运行,而是因为您使用的是箭头函数。箭头函数不仅没有定义自己的函数作用域,也没有arguments

    箭头函数表达式的语法比函数短 表达式并且没有自己的 this、arguments、super 或 新目标。这些函数表达式最适合非方法 函数,它们不能用作构造函数。

    Source

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多