语法错误:参数在字段中无效

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

¥The JavaScript exception "SyntaxError: arguments is not valid in fields" occurs when the arguments identifier is read in a class field initializer or in a static initialization block, outside of a non-arrow function.

信息

¥Message

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)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

类字段初始化表达式或类静态初始化块在其范围内没有 arguments。尝试访问它会导致语法错误。

¥A class field initializer expression or a class static initialization block does not have arguments in its scope. Trying to access it is a syntax error.

  • 即使 arguments 绑定在父范围内(例如当类嵌套在非箭头函数中时),这也是正确的。
  • 在此范围内声明的非箭头函数仍将绑定其自己的 arguments 并正常读取它。

示例

¥Examples

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();
}

也可以看看