Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

Writing in the front

Symbol is the seventh data type provided in JavaScript, following string, Number, Boolean, NULL, undefined, and generalized Object. ECMAScript2020 introduced the eighth data type. Namely BigInt.

The appearance of the Symbol type helps us solve the problem of attribute name conflicts. In this article we will learn about this data type.

The grammar of the Symbol

Basic grammar

The syntax of Symbol is simple. It is a Symbol() function that takes an optional string that describes the Symbol. The following code demonstrates the creation of the Symbol type:

/** * syntax * Symbol([description]) ** description -> is an optional description */
// Create a Symbol value
const mySymbol = Symbol(a)console.log(mySymbol) // Symbol()

const myName = Symbol('Bowl Week')
console.log(typeof myName) // symbol
Copy the code

No two symbols are equal in value.

console.log(Symbol() = = =Symbol()) // false 
console.log(Symbol('Bowl Week') = = =Symbol('Bowl Week')) /// false
Copy the code

Symbol also has the ability to be used as an attribute name for an object. If we use Symbol as the object’s key, there will be no property name conflicts. The sample code looks like this:

const myName = Symbol('Bowl Week')

const person = {
  // It is worth noting that when we use Symbol as the attribute name, we need to calculate the attribute name in the way that Symbol wraps []
  [myName]: 'Bowl Week'
}

console.log(person[myName]) / / a bowl of weeks

Copy the code

Another feature of using Symbol as the attribute name is that it cannot be accessed normally, as shown in the following code:

console.log(Object.keys(person)) / / []
console.log(JSON.stringify(person)) / / {}
Copy the code

This does not mean that it cannot be accessed. You need to use the getOwnPropertySymbols() method provided by Object to access this Object.

console.log(Object.getOwnPropertySymbols(person)) // [Symbol(a bowl)]
Copy the code

In addition to the Object. GetOwnPropertySymbols () provided by the outside also can Reflect ownKeys () method, which also have access to, the following code:

console.log(Reflect.ownKeys(person)) // [Symbol(a bowl)]
Copy the code

For with the keyFor

Symbol provides both for() and keyFor() to create and read symbols registered globally. The for() method checks for existence and returns otherwise.

The following code shows the use of for() and keyFor() :

let myName = Symbol.for("myName");
let object = {
  [myName]: "Bowl week."
};

console.log(object[myName]);       // "One bowl week"
console.log(myName);               // "Symbol(myName)"

let myName2 = Symbol.for("myName");

// The equality here is because myName2's Symbol. For ("myName") is already created. MyName and myName2 refer to the same memory address
console.log(myName === myName2);      // true


console.log(object[myName2]);      // "One bowl week"
console.log(myName2);              // "Symbol(myName)"


// keyFor is used to read, return undefined if not read

console.log(Symbol.keyFor(myName));    // "myName"

console.log(Symbol.keyFor(myName2));   // "myName"

let myName3 = Symbol("myName");

console.log(Symbol.keyFor(myName3));   // undefined
Copy the code

Usage scenarios

Symbol is used to resolve naming conflicts and as a private attribute.

As a private property

The code is as follows:

function getObj () {
  const myName = Symbol('name');
  const obj = {};
  obj[myName] = 'Bowl Week';
  return obj;
}

const obj = getObj();

Object.keys(obj); / / []

// The property cannot be accessed unless the symbol is referenced
obj[Symbol('name')]; // undefined

Copy the code

Resolving naming Conflicts

The code is as follows:

const cache = {}
// a.js
cache['foo'] = 123
// b.js
cache['foo'] = 234

console.log(cache) // { foo: 234 }
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// a.js
cache['a_foo'] = 123
// b.js
cache['b_foo'] = 234

console.log(cache) // { foo: 234, a_foo: 123, b_foo: 234 }
Copy the code

Write in the last

Symbol is the seventh data type supported by JavaScript. It gives me the impression that it optimizes private properties in JS, and that it provides symbol. iterator to define iterators.

Phase to recommend

  • About the V-model syntax sugar knowledge point, this time should say all