I'm studying the new syntax of ES6 and now I'm looking through get
and set
methods and I got an error when trying to use set
method.
Here is an example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(...value) {
this.firstName = firstName;
this.lastName = lastName;
}
}
let a = new Person('Person','A');
a.fullName('Person','B')
console.log(a);
Getters and setters are not used as standard functions. According to MDN:
You should use the normal
=
assignment to invoke the setter, and not call it as a function.In addition, the setter accepts only one paramter, and it can't use the rest (...) syntax. You can use an array of or an object, and use destructuring assignment to achieve that.