Accessors

ArvindNexus8 total contributions
Published Aug 26, 2023
Contribute to Docs
In JavaScript, object properties can be obtained using accessors. Properties are established and retrieved with methods known as “getters” and “setters”.
The get
keyword is used to define a getter method for establishing a custom behavior when accessing the values of object properties, while the set
keyword is used to create a setter method that determines the behavior when assigning values to those properties.
Syntax
There are two ways to access properties: dot notation and bracket notation.
const object = {
get propertyName() {}
}
object.propertyName
object[propertyName]
Example
The following example defines a User
class with a constructor and a getter method. It demonstrates how to encapsulate and access the email information of a user using accessor methods.
class User {constructor(name, email) {this._name = name;this._email = email;}get userEmail() {return this._email;}}console.log(person.userEmail);
This example results in the following output:
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.