SyntaxError: getter functions must have no arguments

当声明的 getter 函数参数列表不为空时,会发生 JavaScript 异常“getter functions must have no arguments”。

消息

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)

错误类型

SyntaxError

哪里出错了?

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

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

示例

无效案例

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

有效情况

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

另见