ES6 learning-Symbol

Symbol

The data type Symbol represents a unique value.

There are two types of object property names, one is the original string, and the other is the newly added Symbol type

It is guaranteed not to conflict with other attribute names.

let s1 = Symbol()
let s2 = Symbol()
console.log(s1, s2, s1 == s2)//Symbol() Symbol() false

Can accept a string as a parameter , representing the description of the Symbol instance

let s1 = Symbol('foo');

If the parameter of Symbol is an object, toStringthe method of the object will be called

const obj = {
    
    
  toString() {
    
    
    return 'abc';
  }
};
const sym = Symbol(obj);
sym // Symbol(abc)

Symbol.prototype.description

Read Symbol's description

const sym = Symbol('foo')
sym.description //foo

as attribute name

let mySymbol = Symbol();
let a = {
    
    };a[mySymbol] = 'Hello!';
let a = {
    
    let a = {
    
    };};
let a = {
    
    };Object.defineProperty(a, mySymbol, {
    
     value: 'Hello!' });

Traversal of property names

for...inSymbol is used as the attribute name. When traversing the object, the attribute will not appear in for...ofthe loop, nor will it be returned by Object.keys(), , Object.getOwnPropertyNames()orJSON.stringify()

Object.getOwnPropertySymbols()method, you can get all the Symbol property names of the specified object. This method returns an array whose members are all Symbol values ​​used as property names of the current object.

const objectSymbols = Object.getOwnPropertySymbols(obj);

Reflect.ownKeys()The method can return all types of keys, including regular keys and Symbol keys

let obj = {
    
    
  [Symbol('my_key')]: 1,
  enum: 2,
  nonEnum: 3
};
Reflect.ownKeys(obj)
//  ["enum", "nonEnum", Symbol(my_key)]

Symbol.for()

Symbol("cat")Each call returns a new value.

Symbol.for()It will first check whether the given one keyalready exists, if it exists: it will return the same Symbol value every time; if it does not exist: it will create a new value.

Symbol.for("bar") === Symbol.for("bar")// true

Symbol("bar") === Symbol("bar")
// false

Since Symbol()the writing method has no registration mechanism , each call will return a different value.

Symbol.keyFor()

Symbol.keyFor()The method returns a registered value of type Symbol key.

let s1 = Symbol.for("foo");
Symbol.keyFor(s1) // "foo"

let s2 = Symbol("foo");
Symbol.keyFor(s2) // undefined

Note that Symbol.for()the names registered for Symbol values ​​are global, whether they are run globally or not.

Guess you like

Origin blog.csdn.net/weixin_46211267/article/details/132161428