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
"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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With