Home > Web Front-end > JS Tutorial > body text

What is symbol used for in js?

下次还敢
Release: 2024-05-07 18:27:19
Original
384 people have browsed it

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

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

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

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

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!