1. An overview of the

Because ES5’s object attribute names are strings, this is prone to attribute name conflicts. For example, if you use an object provided by others, but want to add a new method to the object, the name of the new method may conflict with the existing method, so we have Symbol, which ensures that each attribute name is unique and can fundamentally prevent attribute name conflict.

ES6 introduces a new primitive data type, Symbol, representing unique values, which is the seventh data type of the Javascript language.

The Symbol value is generated by the Symbol function. The property name of the object can now have two types: the original string and the new Symbol type. The Symbol type is unique and does not conflict with other attribute names

let s = Symbol()
typeof s
// 'Symbol'
Copy the code

Note: do not use the new command before the Symbol function, otherwise an error will be reported. Because the generated Symbol is a primitive value, it is not an object. The **Symbol value is not an object and cannot be assigned attributes. ** It is a string-like data type

The Symbol function can take an argument that describes the Symbol instance, which is easily displayed on the console and can be distinguished when converted to a string, as follows:

let s1 = Symbol('foo'); let s2 = Symbol('far'); s1 // Symbol(foo) s2 // Symbol(far) s1.toString() // 'Symbol(foo)' s2.toString() // 'Symbol(far)' // Add a description to tell which Symbol value is printedCopy the code

If the Symbol argument is an object, the object’s toString() method is called to convert it to a string, and the Symbol value is generated

Const obj = {toString() {retrun 'ABC'}} const sym = Symbol(obj) sym // Symbol(ABC) // The parameter to the Symbol function only represents a description of the current Symbol value. Let s1 = Symbol() let s2 = Symbol() s1 === s2 // false let s1 = Symbol('cc') let s2 = Symbol('cc') s1 === s2 // falseCopy the code

Note: The Symbol value cannot be evaluated with other types of values and will report errors. However, the Symbol value can be explicitly converted to a string. In addition, the Symbol value can be converted to a Boolean value, but not to a numeric value.

2. Symbol.prototype.description

You can add a description when creating a Symbol. If you read this description, you need to explicitly convert Symbol to a string. However, this is inconvenient, so in ES2019 we provide the instance attribute Description to return the description of Symbol directly.

// Add description const sym = Symbol('boo') // Read description String(sym) // 'Symbol(boo)' sym.tostring () // 'Symbol(boo)' // Add method sym.description // 'boo'Copy the code

3. Symbol as attribute name

Because each Symbol value is not equal, this means that the Symbol value can be used as an identifier for the property name of the object, which ensures that no property with the same name will appear, preventing a key from being accidentally overwritten or overwritten. As follows:

Let a = {} a[mySymbol] = 'hello' // DefineProperty (a, mySymbol, {value: 'hello'}) // result a[mySymbol] // helloCopy the code

Note: We cannot use the dot operator when using the Symbol value as an object attribute name, and when using the Symbol value to define an attribute, the Symbol value must be enclosed in square brackets. In addition, when the Symbol value is used as the property name, the property is still public, not private.

4. Example: Eliminate magic strings

A magic string is a specific string or number that appears multiple times in the code and is strongly coupled to the code.

function getArea(shape, options) { let area = 0; Switch (shape) {case 'Triangle': // area =.5 * options.width * options.height; break; / *... more code ... */ } return area; } getArea('Triangle', { width: 100, height: 100 }); // Magic stringCopy the code

In the code above, the string Triangle is a magic string that appears multiple times. A “strong coupling” to the code is not conducive to modification and maintenance, and a common approach is to write it as a variable.

const shapeType = {
  triangle: 'Triangle'
};

function getArea(shape, options) {
  let area = 0;
  switch (shape) {
    case shapeType.triangle:
      area = .5 * options.width * options.height;
      break;
  }
  return area;
}

getArea(shapeType.triangle, { width: 100, height: 100 });
Copy the code

Triangle does not matter as long as it does not conflict with other shapeType attributes. Symbol can be used instead.

const shapeType = {
  triangle: Symbol()
};
Copy the code

5. Attribute name traversal

Symbol is the attribute name. This attribute does not appear in for.. in | for… Of loop, will not be the Object. The keys (), Object, getOwnPropertyNames (), JSON. The stringify () returns. But it also has a private property method that gets all Symbol property names for a given object. Object. GetOwnPropertySymbols, it returns an array, members are all used as the Object Symbol value of the property name

const obj = {};
let a = Symbol('a');
let b = Symbol('b');

obj[a] = 'Hello';
obj[b] = 'World';

const objectSymbols = Object.getOwnPropertySymbols(obj);

objectSymbols
// [Symbol(a), Symbol(b)]
Copy the code

We can also use the new API reflect.ownkeys method to return all types of key names, including regular and Symbol key names.

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

Reflect.ownKeys(obj)
Copy the code

Important: Since the Symbol value as a name attribute is not traversed by normal methods, we can use this feature to define non-private methods for objects that we want to use internally only.

6. Symbol. The for (), Symbol keyFor ()

Sometimes we want to reuse the same Symbol value. The symbol. for method does this by taking a string as an argument and searching for a Symbol value named for that argument. If so, return the Symbol value, otherwise create and return a Symbol value with the string name

let s1 = Symbol.for('foo');
let s2 = Symbol.for('foo');

s1 === s2 // true
Copy the code

Symbol. For (); Symbol.

  • The former will be registered in the global environment for search, the latter will not.
  • Symbol.for() does not return a new Symbol value each time it is called. Instead, it checks to see if the given key already exists and creates a new value if it does not.
  • Calling 30 of the symbol.for (‘dog’) returns the same Symbol each time, whereas calling Symbol(‘dog’) returns 30 different symbols.

The symbol.keyfor method returns a key of the registered Symbol type that corresponds to symbol.for ().

let s1 = Symbol.for('foo')
Symbol.keyFor(s1)   // 'foo'

let s2 = Symbol('foo')
Symbol.keyFor(s2)   // undefined
Copy the code

7. The module’s Singleton pattern

The Singleton pattern refers to invoking a class that returns the same instance at all times. This can be done by placing the instance on the top-level object, Global.

8. Built-in Symbol value

8.1. The Symbol. HasInstance

An internal method that is called when another object uses the instanceof operator to determine whether it is an instanceof that object.

8.2. The Symbol. IsConcatSpreadable

Is a Boolean value that indicates whether the object can be expanded when used with array.prototype.caocat ()

  • The default behavior of an array can be expanded.
  • Objects in class arrays are not expanded by default.

8.3. The Symbol. The species

Points to a constructor that is used when creating derived objects. It does this by calling the constructor specified by this property when the instance object needs to call its own constructor again during execution. Its main use is that some libraries are modified from the base class. So when a subclass uses an inherited method, it wants to return an instance of the base class, not an instance of the subclass.

8.4. The Symbol. The match

Refers to a function that is called when str.match(myObject) is executed, if the property is present, and returns the return value of the method.

8.5. The Symbol. The replace

Object that points to a method. When an object is called by the String.prototype.replace method, the value of that method is returned.

8.6. The Symbol. The search

Object that points to a method whose value is returned when called by the String.prototype.search method

8.7. The Symbol. The split

The symbol.split object calls the symbol.split property, pointing to a method whose value is returned when called by the String.prototype.split method.

8.8. The Symbol. The iterator

Object that points to the default traverser method for that object

8.9 Symbol. ToPrimitive

Object’s symbol. toPrimitive property, pointing to a method. This method is called when the object is converted to a value of the original type, returning the corresponding value of the original type of the object. When symbol.toprimitive is called, it takes a string argument representing the current operation mode, of which there are three.

  • Number: Converts to a value in this case
  • String: Converts to a String in this case
  • Default: The value can be converted to a value or a string

8.10 Symbol. ToStringTag

Object that points to a method. Call on the Object Object. The prototype. The toString method, if the property exists, it returns a value will appear in the toString () method returns the string, the type of the Object. That is, this property can be used to customize the string after object in object object or object Array.

8.11. The Symbol. Unscopables

Object, pointing to an object that specifies which properties are excluded from the with environment when the with keyword is used.

Welcome to pay attention to the public account [Xiaoyao students]

Re-learn js series

Relearn JS JavaScript introduction

Relearn JS to use JavaScript in HTML

Data types => Data types

Relearn the basic JavaScript concepts of JS (middle) => operator

Relearn the basic JavaScript concepts of JS (part 2) => operator

ES6 Introduction series

ES6 Introduction to let and cont

ES6 introduction to variable deconstruction assignment

ES6 starter string extension

ES6 – An extension to get started with re

ES6 introduction to numerical extension

Extension of ES6 introductory functions

ES6 introduction to the array extension

Extensions to ES6 starter objects

New methods for ES6 entry objects

Git tutorial

Front-end Git basics tutorial