Symbol common methods and characteristics

Reference to reprint Symbol address:
https://es6.ruanyifeng.com/#docs/symbol
ES6 introduces a new primitive basic data Symbol, which is the seventh data type of the JavaScript language. The first six are: undefined, null , Boolean, String, Number, Object.
Today I sorted out some of the more commonly used features and methods of Symbol.

Symbol awareness

  1. Uniqueness
 const s = Symbol(); //创建一个Smbol类型的数据
 console.log(s)
 const x = Symbol();

Insert picture description here

  1. Each Symbol value has a tag string, which is obtained through the Symbol.description property
  // 给Symbol类型的数据分配一个字符串
        const c = Symbol('foo');
        const d = Symbol('rdd');
        console.log(c.description)
        console.log(d.description)

Insert picture description here

  1. When Symbol is used as a property name, you must add [].
    Object properties (instance properties) generally have only two types: string.
    Insert picture description here
    Insert picture description here
    If Symbol is assigned like this , if you want to get 90, you can deconstruct it:
  obj[Symbol()] = 90

Insert picture description here

  1. Symbol.for()
    It will be registered with a marked string.
    Not only is it a Symbol value, but also a one-
    to-one correspondence between the string in for and the Symbol. Accepts a string and returns a Symbol value. At the same time, it will register a global correspondence between the string and the Symbol value.
    If the string has already been registered, return its corresponding Symbol value
 // 注册Symbol与字符串的关系
        const e = Symbol.for('e')
        const f = Symbol.for('e')
        console.log(e === f)//true

Insert picture description here

  1. Symbol.keyFor():
    Returns the registered key, accepts a Symbol value, and returns its corresponding string for the Symbol value generated by fro
    Insert picture description here
  2. According to the attribute name, the
    attribute name is a string type, and the
    attribute name is a symbol type.
    By obj.getOwnPropertySymbol obtaining its own attribute Symbol value, obtaining the attribute of the instance itself with the Symbol type as the key
  object.getOwnPropertySymbol(obj)

Insert picture description here

Guess you like

Origin blog.csdn.net/Menqq/article/details/111051713