语法错误:getter 函数不能有参数

当声明 getter 并且参数列表非空时,会发生 JavaScript 异常 "getter 函数不能有参数"。

¥The JavaScript exception "getter functions must have no arguments" occurs when a getter is declared and the parameter list is non-empty.

信息

¥Message

SyntaxError: Getter must not have any formal parameters. (V8-based)
SyntaxError: getter functions must have no arguments (Firefox)
SyntaxError: Unexpected identifier 'x'. getter functions must have no parameters. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

get 属性语法看起来像一个函数,但它更严格,并且并非所有函数语法都允许。getter 总是在没有参数的情况下调用,因此使用任何参数定义它都可能是一个错误。

¥The get property syntax looks like a function, but it is stricter and not all function syntax is allowed. A getter is always invoked with no arguments, so defining it with any parameter is likely an error.

请注意,此错误仅适用于使用 get 语法的属性获取器。如果你使用 Object.defineProperty() 等定义 getter,则 getter 被定义为普通函数,尽管如果 getter 需要任何参数,它仍可能是一个错误,因为它将在没有任何参数的情况下被调用。

¥Note that this error only applies to property getters using the get syntax. If you define the getter using Object.defineProperty(), etc., the getter is defined as a normal function, although it's likely still an error if the getter expects any arguments, as it will be called without any.

示例

¥Examples

无效案例

¥Invalid cases

js
const obj = {
  get value(type) {
    return type === "string" ? String(Math.random()) : Math.random();
  },
};

有效案例

¥Valid cases

js
// Remove the parameter
const obj = {
  get value() {
    return Math.random();
  },
};

// Use a normal method, if you need a parameter
const obj = {
  getValue(type) {
    return type === "string" ? String(Math.random()) : Math.random();
  },
};

也可以看看

¥See also