Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Setter must have exactly one formal parameter

I'm trying to understand getters and setters on JS and I can't seem to get pass this error. Can anyone provide any insight as to why I'm getting this error?

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

like image 508
Dinna Avatar asked Nov 19 '15 21:11

Dinna


People also ask

What is formal parameters in JavaScript?

"Formal parameter" is a fancy way of saying "function parameter". Your function declaration is missing valid parameters. In the declaration of a function, the parameters must be identifiers, not any value like numbers, strings, or objects. Declaring functions and calling functions are two separate steps.

What is a formal parameter name?

formal parameter — the identifier used in a method to stand for the value that is passed into the method by a caller. For example, amount is a formal parameter of processDeposit.

What is a setter in JS?

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.


1 Answers

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

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

As you can see it doesn't make sense for a setter to take multiply arguments, but it gives you the freedom to manipulate the value before it is set:

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"
like image 77
Andreas Louv Avatar answered Nov 14 '22 19:11

Andreas Louv