Symbol solves two problems:

  1. uniqueness
  2. Use the Symbol attribute to manipulate the internal JavaScript logic

The appearance of this feature makes general sense for defining programs. It is a primitive type, just like the original six primitive types, which you can initialize by calling Symbol().

let v = Symbol('icepy')
Copy the code

uniqueness

We know that in the JavaScript world, uniqueness is hard to describe, even if you use any encryption function to generate the Key can be hit library, Symbol gives us such uniqueness:

let name = Symbol('name');
let max = Symbol(a);
let obj = {
  [name]:'icepy'.
  [max]: 29
}

// Symbol()
Copy the code

Symbol can accept a parameter for DES, which is used mainly for tracing during program debugging. Of course, you can pass no parameter. Similarly, we can use typeof to determine whether it is Symbol type.

The Symbol property provides a for method to handle global sharing. This method searches the specific contents of the Symbol registry, whereas you can use keyFor to infer the key associated with a Symbol.

Use the Symbol attribute to manipulate the internal JavaScript logic

In the past, it was difficult to manipulate the internal logic of the JavaScript language. At most, we define or modify the implementation of a method in the prototype chain. Symbol provides a lot of logic to handle the internal implementation of the program. Symbol, Symbol, Symbol, Symbol

In the old days when we wanted to determine an array, we might write:

let f = []
Object.prototype.toString.call(f)
// "[object Array]"
Copy the code

We could define [object Array], but let’s say we’re writing some applications today, and I want to type some classes, and by typing, I want to solve some problems, and at first we could use instance to tell which instance it is, but that’s not going to solve the problem.

After a Symbol attribute, we can change the Object. The prototype. ToString return values.

function Pre() {
}
Pro.prototype[Symbol.toStringTag] = 'Pre';

const me = new Pre(a);

// Object.prototype.toString.call(me) 
// [object Pre]
Copy the code

Maybe in this rough example, it is hard to see the function of Symbol.

However, I mentioned earlier that instance can be used to determine if it is an instance of a class or function. One day I want to give it a true instance, I want it to return false, i.e., not an instance.

function Pre() {

}
Object.defineProperty(Pre.Symbol.hasInstance, {
  value: function() {
     return false
  }
})
Copy the code

This is one of the functions of Symbol to change the logic inside language programs.

These features are probably rarely used in your real-world applications, but it doesn’t hurt to take a look.

For more exciting content, please follow my wechat official account: search Fed-Talk