Symbol Detailed Explanation and Usage

Foreword:

The attribute names of objects in ES5 are all strings, which is easy to cause duplicate names and pollute the environment

1. What is Symbol?

Symbol is a new basic data type introduced in ES6, which is used to represent a unique value. It is the seventh data type in JavaScript, alongside undefined, null, Number (value), String (string), Boolean (Boolean), and Object (object).


Second, the characteristics of Symbol

  1. The value corresponding to the Symbol attribute is unique, which solves the problem of naming conflicts
let symbol = Symbol("one")
let symbol1 = Symbol("one")
console.log(symbol)
// 结果:Symbol("one")
  1. Symbol values ​​cannot be calculated with other data, including matching strings
let a = Symbol()
let b = a+1
console.log(b)
// 结果:报错
  1. For in, for of does not traverse symbol attributes when traversing.
let symbol = Symbol();
let obj = {};
obj[symbol] = 'hello';

for(var i in obj){
	console.log(obj[i])
}
// 结果:报错

3. The use of Symbol

  1. Call the Symbol function to get the symbol value
let symbol = Symbol();
let obj = {};
obj[symbol] = 'hello';

for(var i in obj){
	console.log(obj[i])
}
// 结果:报错
  1. Parameter ID
let symbol = Symbol('one');
let symbol2 = Symbol('two');
console.log(symbol);// Symbol('one')
console.log(symbol2);// Symbol('two')
  1. Built-in Symbol value
  • In addition to defining the Symbol value used by itself, ES6 also provides 11 built-in Symbol values, which point to the methods used internally by the language.
    • Symbol.iterator
  • The Symbol.iterator property of the object points to the object's default traverser method (described later)
  1. symbol != symbol symbol is unique
let one = Symbol("one")
let two = Symbol("one")

console.log(one == two)
// 结果:false
  1. Create the attribute value of symbol
let symbol = Symbol()
   
let obj = {name:"张三疯",age:18}
  1. fon in for of will not traverse symbols
obj[symbol] = "123"
console.log(obj)
for(var v in obj){
   console.log(obj[v])
}
// 结果:报错
  1. Symbol values ​​cannot be operated on with values ​​of other types
let obj = {
	toString(){
		return "123"
	}
}
let a = Symbol(obj)
console.log(a+'1234')
// 结果:报错
  1. Symbol values ​​can be explicitly converted to strings.
let obj = {
	toString(){
		return "123"
	}
}
let a = Symbol(obj)

console.log(String(a))
// Symbol(123)
console.log(a == String(a))
// false

Summarize:

That's allDetailed explanation and usage of the new Symbol in ES6If you don’t understand, you can ask me in the comment area or chat with me privately. I will continue to release some new functions in the future, so stay tuned.
My other articles: https://blog.csdn.net/weixin_62897746?type=blog

Guess you like

Origin blog.csdn.net/weixin_62897746/article/details/128845162