Uncaught SyntaxError: Setter must have exactly one formal parameter

Uncaught SyntaxError: Setter must have exactly one formal parameter

我正在尝试了解 JS 上的 getter 和 setter,但我似乎无法通过此错误。任何人都可以提供关于为什么我会收到此错误的任何见解吗?

var book = {
    year: 2004,
    edition:1,
    get newYear(){
        return "Hello, it's " + this.year;
    },
    set newYear(y, e){
        this.year = y;
        this.edition = e;
    }
};

Uncaught SyntaxError: Setter must have exactly one formal parameter

A setter 函数是一个在您执行以下操作时隐式调用的函数:

someObject.property = 25;

因为赋值操作只涉及分配一个值,所以 setter 函数必须有一个参数。无论如何,它只会被调用(通过隐式赋值机制)一个参数,所以两个参数 setter 没有什么意义。

在您的情况下,您可以让 setter 获取单个对象并从中获取两个值:

var book = {
    year: 2004,
    edition:1,
    get newYear(){
        return "Hello, it's " + this.year;
    },
    set newYear(value){
        this.year = value.y;
        this.edition = value.e;
    }
};

那你可以说

book.newYear = { y: 2005, e: 2 };

(我个人认为我更愿意通过解构赋值来做到这一点,但它会起作用。)

当您分配 setter 表示的值时调用 setter 函数:

var obj = {
  set a(newVal) { console.log("hello"); }
}
obj.a = 1; // will console log "hello"

如您所见,setter 接受多个参数是没有意义的,但它使您可以在设置值之前自由地操作该值:

var person = {
  surname: "John",
  lastname: "Doe",
  get fullname() {
    return this.surname + " " + this.lastname;
  },
  set fullname(fullname) {
    fullname = fullname.split(' ');
    this.surname = fullname[0];
    this.lastname = fullname[1];
  }
};

console.log(person.fullname); // "John Doe"
person.fullname = "Jane Roe";
console.log(person.surname); // "Jane"
console.log(person.lastname); // "Roe"

尝试 setNewYear 而不是设置 newYear 和同样的 getNewYear 而不是获取 newYear。