Home >Web Front-end >JS Tutorial >How Do I Create and Access Private Properties in JavaScript ES6 Classes?
Private Properties in JavaScript ES6 Classes
Introduction
In previous JavaScript versions, class properties were always accessible within the same class instance and from other instances and classes. However, with the introduction of ES6, private properties can now be created, limiting access to specific properties within a class.
Creating Private Properties
To create a private property in an ES6 class, prefix the property name with a hash (#). This syntax indicates that the property is private and should not be accessed directly.
For example, consider the following code:
class Something { constructor() { this.#property = "test"; // private property } }
In this example, the property attribute is prefixed with a hash, making it inaccessible outside the class.
Accessing Private Properties
Private properties cannot be accessed directly from outside the class. However, you can use getter methods to retrieve the value of a private property.
For instance, to access the property private value in the previous example, we can add the following getter method to the class:
class Something { constructor() { this.#property = "test"; // private property } get property() { return this.#property; } }
Now, we can access the private property value using the property getter method:
const instance = new Something(); console.log(instance.property); // Output: "test"
Additional Notes
The above is the detailed content of How Do I Create and Access Private Properties in JavaScript ES6 Classes?. For more information, please follow other related articles on the PHP Chinese website!