sd1sd1
sd1sd1

Reputation: 1048

es6 javascript setter function outside constuction

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

Upvotes: 0

Views: 201

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370689

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.

Upvotes: 3

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4806

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

friends.partner = 75;

Upvotes: 0

Related Questions