ES6 setter function isn't recognized

622 views Asked by At

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);
3

There are 3 answers

8
Ori Drori On BEST ANSWER

Getters and setters are not used as standard functions. According to MDN:

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

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.

class Person {

  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  
  set fullName([firstName, lastName]) {
    this.firstName = firstName;
    
    this.lastName = lastName;
  }
}

let a = new Person('Person','A');

a.fullName = ['Person', 'B'];

console.dir(a);

4
Estus Flask On

It isn't entirely new syntax. It is a variation of ES5 setter that was applied to ES6 classes.

The whole point of get/setproperty accessors is that they are defined as property descriptor and used as ordinary property:

console.log(person.fullName);
person.fullName = 'Foo Bar';

And it should be:

set fullName(value) {
    const [firstName, lastName] = value.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;
}

It makes no sense to define it as set setter if you want to use it as ordinary method. Instead, it can be

setFullName(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}
0
aesede On

You can't use a setter like that, see my snippet below and see this answer for an explanation

class Person {
 constructor(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
 }

 get fullName() {
  return `${this.firstName} ${this.lastName}`;
 }

 set fullName(fname) {
        let fn = fname.split(' ');
  this.firstName = fn[0];
  this.lastName = fn[1];
 }
}

let a = new Person('Person','A');
a.fullName = 'Person B';
console.dir(a);