Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are getters and setters for in ECMAScript 6 classes?

I am confused as to what the point of getters and setters are in ECMAScript 6 classes. What is the purpose? Below is an example I am referring to:

class Employee {      constructor(name) {         this._name = name;     }      doWork() {         return `${this._name} is working`;     }      get name() {         return this._name.toUpperCase();     }      set name(newName){         if(newName){              this._name = newName;         }     } } 
like image 604
TruMan1 Avatar asked Jan 29 '15 18:01

TruMan1


People also ask

What is the purpose of getters and setters in a class?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

What is the point of getters and setters in JavaScript?

They are code constructs that help developers access the properties of objects in a secure way. With getters, you can access (“get”) the values of properties from external code, while setters let you change (“set”) their values.

Do JavaScript classes need getters and setters?

Classes allow using getters and setters. It is smart to use getters and setters for the properties, especially if you want to do something special with the value before returning them, or before you set them.

What's the advantage of using getters and setters?

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. 2.


1 Answers

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

var emp = new Employee("TruMan1");  if (emp.name) {    // uses the get method in the background }  emp.name = "New name"; // uses the setter in the background 

This is only to set and get the value of the property.

like image 152
David Laberge Avatar answered Sep 18 '22 15:09

David Laberge