SyntaxError: arguments is not valid in fields

当在类字段初始化器或静态初始化块中,非箭头函数之外读取 arguments 标识符时,会发生 JavaScript 异常“SyntaxError: arguments 在字段中无效”。

消息

SyntaxError: 'arguments' is not allowed in class field initializer or static initialization block (V8-based)
SyntaxError: arguments is not valid in fields (Firefox)
SyntaxError: Unexpected identifier 'arguments'. Cannot reference 'arguments' in class field initializer. (Safari)

错误类型

SyntaxError

哪里出错了?

类字段初始化器表达式或类静态初始化块在其作用域中不包含 arguments。尝试访问它会引发语法错误。

  • 即使 arguments 在父级作用域中绑定(例如当类嵌套在非箭头函数中时),此规则也适用。
  • 在此作用域内声明的非箭头函数仍将绑定其自己的 arguments 并正常读取它。

示例

js
function makeOne() {
  class C {
    args = { ...arguments }; // SyntaxError: arguments is not valid in fields
  }
  return new C();
}
js
let CArgs;
class C {
  static {
    CArgs = arguments; // SyntaxError: arguments is not valid in fields
  }
}
js
class C {
  args = {};
  constructor() {
    this.args = arguments; // You can use arguments in constructors
  }
  myMethod() {
    this.args = arguments; // You can also use it in methods
  }
}
js
function makeOne() {
  const _arguments = arguments;
  class C {
    args = { ..._arguments }; // Only the identifier is forbidden
  }
  return new C();
}

另见