Reading notes: in-depth understanding of ES6 (6)

Chapter 6 Symbol and Symbol Attributes

Section 1 Create Symbol

  1.1 Symbol refers to private properties in ES6

  1.2 Create grammar:

 let firstName = Symbol();
 let person = {};
 
 person[firstName] = "zxx";
 console.log(person[firstName]); //"zxx"

 

Section 2 How to use Symbol

  Symbol can be used wherever a computable attribute name is used . For example:

  let firstName = Symbol("first name");
  
  //使用一个可计算对象字面量属性
  let person = {
      [firstName]: "zxx"
  };
  
  //将属性设置为只读
  Object.defineProperty(person, firstName, {writable: false});
 
 console.log( person[firstName] ); // "zxx"

 

Section 3 Symbol Sharing System

   3.1 Why create a Symbol sharing system?

    Sometimes we may want to share the same Symbol in different codes. ES6 provides a global Symbol registry that can be accessed at any time. It is a shared environment similar to the global scope. If you want to create a symbol that can be shared, use the Symbol.for() method. It only accepts the parameters to be given, that is, the identifier of the symbol string to be created. For example:

 let uid = Symbol.for("uid");
 let object = {};
 Object[uid] = "12345";
 
 console.log( Object[uid] ); //"12345"
 console.log( uid ); //  "Symbol(uid)"

 

Section 4 Symbol and type coercion

  In JavaScript, there is no logically equivalent value to Symbol, so Symbol is not very flexible to use, especially Symbol cannot be coerced into string and number types.

 

Section 5 Symbol attribute retrieval

  In ES6, the Object.getOwnPropertySymbols() method was added, which returns an array containing all Symbol's own properties. For example:

 let uid = Symbol.for("uid");
 let object = {
     [uid]: "12345"
 };
 let symbols = Object.getOwnPropertySymbols(object);
 
 console.log( symbols.length ); // 1
 console.log( symbols[0] ); // "Symbols(uid)"
 console.log( object[symbols[0]] ); // "12345"

 

Section 6 exposes its internal operations through well-known Symbol

  6.1 ES6 extends ES5 to "expose some of the'magic' parts of JS, and similarly define the functions that these developers could not simulate at the time". In the new standard, it is mainly defined on the prototype chain. Symbol-related attributes to expose more internal logic of the language.

  6.2 Some specific methods are similar to APIs, you can refer to p.113-p.127 when you use them.

 

(End of this section)

Guess you like

Origin blog.csdn.net/ZxxSteven/article/details/100576725