0

is it possible to call the setter function outside the constructor class?

i.e. i have the following class

class example {
  constructor() {
    this._partner = 0;
   }
   get partner() {
    return this._partner;
   }

  set partner(id) {
    this._partner = id;
  }
}

when i call

friends = new example();
freinds.partner(75);

i see the follwing error:

 Uncaught TypeError: example.partner is not a function
sd1sd1
  • 1,028
  • 3
  • 15
  • 28

2 Answers2

3

To invoke a setter/getter, it has to look from the outside as if you're directly setting or retrieving a property on the object (not calling a function):

class example {
  constructor() {
    this._partner = 0;
   }
   get partner() {
    console.log('getter running');
    return this._partner;
   }

  set partner(id) {
    console.log('setter running');
    this._partner = id;
  }
}

friends = new example();
console.log('about to assign to .partner');
friends.partner = 75;
console.log('about to retrieve .partner');
console.log(friends.partner);

Note that the parameter that the setter sees is the value that looks like got "assigned" to the property outside.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

These setter and getter allow you to use the properties directly (without using the parenthesis)

friends.partner = 75;
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23