Home > Web Front-end > JS Tutorial > How Do I Create and Access Private Properties in JavaScript ES6 Classes?

How Do I Create and Access Private Properties in JavaScript ES6 Classes?

Susan Sarandon
Release: 2024-12-27 08:11:09
Original
851 people have browsed it

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
  }
}
Copy after login

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;
  }
}
Copy after login

Now, we can access the private property value using the property getter method:

const instance = new Something();
console.log(instance.property); // Output: "test"
Copy after login

Additional Notes

  • Private methods can also be created using the same hash syntax.
  • Private properties and methods are not enumerable (i.e., they won't appear when iterating over object properties).
  • As of ES2023, private fields are supported in the majority of browsers.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template