Uncaught SyntaxError: Setter must have exactly one formal parameter

I am trying to understand getters and setters in JS and I cannot miss this error. Can someone give an idea of ​​why I am getting this error?

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

Uncaught SyntaxError: Setter must have exactly one formal parameter

+4
source share
3 answers

The setter function is called when you assign a value that the setter represents:

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

As you can see, it does not make sense for the setter to accept arguments with multiple arguments, but it gives you the freedom to manipulate the value before setting it:

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"
+4
source

The setter function is a function that is called implicitly when you do something like:

someObject.property = 25;

, setter . - ( ) , .

:

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

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

( , , .)

+4

setNewYear newYear getNewYear newYear.

0

Source: https://habr.com/ru/post/1616633/


All Articles