Welcome to wechat public account: Front Reading Room

Symbols

introduce

Since ECMAScript 2015, symbol has become a new primitive type, just like number and String.

The value of the symbol type is created through the Symbol constructor.

let sym1 = Symbol(a);let sym2 = Symbol("key"); // The optional string key
Copy the code

The Symbols are immutable and unique.

let sym2 = Symbol("key");
let sym3 = Symbol("key");

sym2 === sym3; // False, symbols are unique
Copy the code

Like strings, Symbols can also be used as keys for object properties.

let sym = Symbol(a);let obj = {
    [sym]: "value"
};

console.log(obj[sym]); // "value"
Copy the code

Symbols can also be combined with computed property name declarations to declare attributes and class members of an object.

const getClassNameSymbol = Symbol(a);class C {
    [getClassNameSymbol](){
       return "C"; }}let c = new C();
let className = c[getClassNameSymbol](); // "C"
Copy the code

Symbols, as we all know

In addition to the user defined symbols, there are several built-in symbols that are already well known. The built-in symbols are used to represent behavior within the language.

Here is a list of these symbols:

  • Symbol.hasInstance

Method, which is called by the instanceof operator. The constructor object is used to identify whether an object is an instance.

  • Symbol.isConcatSpreadable

Boolean value indicating whether the Array elements of an object can be expanded when array.prototype. concat is called on the object.

  • Symbol.iterator

Method, called by the for-of statement. Returns the default iterator for the object.

  • Symbol.match

Method, called by string.prototype. match. Regular expressions are used to match strings.

  • Symbol.replace

Method, called by string.prototype. replace. Regular expressions are used to replace matched substrings in a string.

  • Symbol.search

Method, called by string.prototype. search. The regular expression returns the index of the matched portion in the string.

  • Symbol.species

Function value, which is a constructor. Used to create derived objects.

  • Symbol.split

Method, called by string.prototype.split. Regular expressions to split strings.

  • Symbol.toPrimitive

Method, called by the ToPrimitive abstract operation. Converts an object to its corresponding original value.

  • Symbol.toStringTag

Method by the built-in Object. The prototype. ToString calls. Returns the default string description when the object is created.

  • Symbol.unscopables

Object, whose own properties are excluded from the with scope.

Welcome to wechat public account: Front Reading Room