ES6: How much do you know about Symbol?
Overview
ES6 introduces a new primitive data type Symbol, which represents a unique value. In other words, the object attribute name can have two types: one is the original string, and the other is the newly-added Symbol type, which can guarantee that it will not conflict with other attribute names.
The Symbol function can accept a string as a parameter, which represents the description of the Symbol instance, mainly for displaying on the console or for easier distinction when converting to a string.
let s = Symbol('foo');
typeof s //symbol
s //Symbol(foo)
s.toString() //"Symbol(foo)"
String(s) //"Symbol(foo)"
If the parameter of the Symbol is an object, the toString method of the object will be called to convert it into a string, and then the symbol will be generated.
const obj = {
toString(){
return 'abc'
}
}
let sym = Symbol(obj);
sym //Symbol(abc)
Symbol as the attribute name
Since each Symbol value is not equal, it means that the Symbol value can be used as an identifier for the attribute name of the object, ensuring that no attribute with the same name will appear. However, the Symbol property is not allowed to be accessed with the dot operator
var mysym = Symbol();
//下面三种写法都可以
var a = {
}
a[mysym] = 'hello';
var a = {
[mysym] : 'hello'
};
var a = {
}
Object.defineProperty(a,mysym,{
value: 'hello'});
//相同的结果
a[mysym] //'hello'
Traversal of attribute names
Symbol name as a property, the property does not appear in for... in
or for...of
in, will not be Object.keys()
, Object.getOwnPropertyNames()
returned. However, there is a Object.getOwnPropertySymbols
method that returns the Symbol property name of the specified object.
var obj = {
};
var a = Symbol('a');
var b = Symbol('b');
obj[a] = "hello";
obj[b] = "world";
var symbols = Object.getOwnPropertySymbols(obj);
symbols //[Symbol(a),Symbol(b)]
Another new API: Reflect.ownKeys
methods can return all types of key names, including regular key names and Symbol key names.
let obj = {
[Symbol('a')] : 1,
num : 2
}
Reflect.ownKeys(obj) //["num",Symbol(a)]
Appeared! Let the unique share!
Sometimes, we want to reuse the same Symbol value, and the Symbol.for
method can do this. It accepts a string as a parameter, and then searches for a Symbol value with the parameter as the name. If there is, return the Symbol value, otherwise, create a new well and return a Symbol value named after the string.
var s1 = Symbol.for('foo');
var s2 = Symbol.for('foo');
s1 === s2 //true
Symbol.for('foo') === Symbol.for('foo') //true
Symbol('foo') === Symbol('foo') //false