- Learning JavaScript Data Structures and Algorithms
- Loiane Groner
- 241字
- 2021-08-27 18:41:10
Working with getters and setters
It is also possible to create getter and setter functions for the class attributes with ES2015. Although class attributes are not private as in other object-oriented languages (the encapsulation concept), it is good to follow a naming pattern.
The following is an example of a class declaring a get and set function along with its use:
class Person { constructor(name) { this._name = name; // {1} } get name() { // {2} return this._name; } set name(value) { // {3} this._name = value; } } let lotrChar = new Person('Frodo'); console.log(lotrChar.name); // {4} lotrChar.name = 'Gandalf'; // {5} console.log(lotrChar.name); lotrChar._name = 'Sam'; // {6} console.log(lotrChar.name);
To declare a get and set function, we simply need to use the keyword get or set in front of the function name (lines {2} and {3}), which is the name we want to expose and to be used. We can declare the class attributes with the same name, or we can use an underscore in front of the attribute name (line {1}) to make it feel like the attribute is private.
Then, to use the get or set functions, we can simply refer to their names as if it was a simple attribute (lines {4} and {5}).
The _name attribute is not private, and we can still access it (line {6}). However, we will talk about this later on in this book.