Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  52] [ 7]  / answers: 1 / hits: 16095  / 9 Years ago, thu, november 19, 2015, 12:00:00

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



More From » setter

 Answers
82

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

[#64334] Wednesday, November 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cierra

Total Points: 504
Total Questions: 108
Total Answers: 109

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;