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; } } }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With