Home >Web Front-end >JS Tutorial >What is symbol used for in js?

What is symbol used for in js?

下次还敢
下次还敢Original
2024-05-07 18:27:19437browse

Symbol is used as an immutable unique identifier in JavaScript. Its main uses include: as a private property of an object, identifying class members, mapping keys, generator function return values, and other built-in object properties.

What is symbol used for in js?

The use of Symbol in JavaScript

Symbol is a unique value type in JavaScript. It is essentially Is an immutable, unique identifier. Its main uses are:

1. As a private property of an object

Symbol can be used as a private property of an object because it does not appear in the standard for...in loop or Object.keys() method. This makes it ideal for storing sensitive data or for internal state management.

Sample code:

<code class="js">const user = {
  [Symbol("secretData")]: "Confidential information"
};</code>

2. As an identifier for class members

Symbol can be used to identify objects in a class Members, such as methods or properties. This prevents accidental overwrites or conflicts.

Sample code:

<code class="js">class Person {
  static [Symbol("getName")]() {
    return "John Doe";
  }
}</code>

3. As a mapping key

Symbol can be used as a mapping (Map or WeakMap) key. This is useful for creating more readable and maintainable code.

Sample code:

<code class="js">const myMap = new Map();
myMap.set(Symbol("key1"), "value1");</code>

4. As the return value of the generator function

Symbol can be used as the generator function The return value represents the unique identifier of an iterable object.

Sample code:

<code class="js">function* myGenerator() {
  yield 1;
  yield 2;
}

const mySymbol = Symbol.iterator;
const myIterator = myGenerator()[mySymbol]();</code>

5. As a property of other built-in objects

Symbol is also used as a property of other built-in objects Properties, for example:

  • Symbol.iterator: Represents the default iterator of the object
  • Symbol.hasInstance: Used to check the object Whether it is an instance of the specified class
  • Symbol.species: Returns the constructor of the object

The above is the detailed content of What is symbol used for in js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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