【问题标题】:Behaviour Difference For Arrow-Functions vs Functions In Javascript [duplicate]Javascript中箭头函数与函数的行为差异[重复]
【发布时间】:2018-11-26 21:17:46
【问题描述】:

我想了解普通函数与箭头函数的行为。

箭头功能:

function arrowFunc() {
  return () => arguments
}


console.log(arrowFunc(1, 2, 3)(1))

正态函数

function normalFunc() {
  return function() {
    return arguments
  }
}

console.log(normalFunc(1, 2, 3)(1))

两个结果都应该是相同的,但看起来上面定义的 arrowFunc 考虑了第一个 arg 列表,而 normalFunc 考虑了第二组 arg 列表。

也尝试了 babel-compilation 来理解差异,但看起来行为不同,如下所示:

Babel 输出:

"use strict";

function arrowFunc() {
  var _arguments = arguments;

  return function() {
    return _arguments;
  };
}

console.log(arrowFunc(1, 2, 3)(1));

function normalFunc() {
  return function() {
    return arguments;
  };
}

console.log(normalFunc(1, 2, 3)(1));

【问题讨论】:

  • Both the results are expected to be same 不,箭头函数没有arguments。就像this,如果存在外部arguments,它只会引用外部绑定

标签: javascript arrow-functions


【解决方案1】:

两个结果应该是一样的

不,他们不是。


MDN 箭头函数页面的第一行(强调我的):

箭头函数表达式的语法比函数短 表达式并且没有自己的thisargumentssuper,或 new.target.

在同一页面的下方:

箭头函数没有自己的arguments 对象。因此,在 在这个例子中,arguments 只是一个对 封闭范围 [...]

而在ECMAScript specification

注意:箭头函数永远不会有参数对象。 (原文如此)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2021-03-29
    • 2023-03-08
    • 1970-01-01
    • 2020-03-07
    • 2023-03-12
    • 1970-01-01
    • 2018-02-07
    相关资源
    最近更新 更多