Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use getters and setters in JavaScript?

I know how getter and setter work in JavaScript. What I don't understand is why we need them when we can get the same result using normal functions? Consider the following code:

var person = {     firstName: 'Jimmy',     lastName: 'Smith',     get fullName() {         return this.firstName + ' ' + this.lastName;     } }  console.log(person.fullName);    // Jimmy Smith 

We can easily replace getter with a function:

var person = {     firstName: 'Jimmy',     lastName: 'Smith',     fullName: function() {         return this.firstName + ' ' + this.lastName;     } }  console.log(person.fullName());    // Jimmy Smith 

I don't see the point of writing getter and setter.

like image 332
NL500 Avatar asked Feb 20 '17 10:02

NL500


People also ask

Why do we need getters and setters in JavaScript?

The main benefit of using getter and setter is that we can implement some logic before and after getting and setting the value of a property.

What is the advantage of using getter and setter?

The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.

What is the purpose of usage getters for JavaScript objects?

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed.


Video Answer


1 Answers

A difference between using a getter or setter and using a standard function is that getters/setters are automatically invoked on assignment. So it looks just like a normal property but behind the scenes you can have extra logic (or checks) to be run just before or after the assignment.

So if you decide to add this kind of extra logic to one of the existing object properties that is already being referenced, you can convert it to getter/setter style without altering the rest of the code that has access to that property.

Edit: Here is an example for an extra logic, this class counts how many times its name is read:

class MyClass {    constructor() {      this.refCount = 0;      this._name = 'the class';    }      get name() {      this.refCount++;      console.log(`name is read ${this.refCount} times.`);      return this._name;    }  }    const myClass = new MyClass();    let maxMessages = 5;  const t = setInterval(() => {    console.log(`name: ${myClass.name}`);        if (--maxMessages < 1) {      console.log('done');      clearInterval(t);    }  }, 1000);
like image 128
Bulent Vural Avatar answered Oct 14 '22 00:10

Bulent Vural