es6 symbol belongs to the basic type. Symbol is a new basic data type introduced in es6, which represents a unique value; its function is to prevent attribute name conflicts and ensure that each attribute name in the object is unique.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Symbol
is a basic data type, a new data type introduced in ES6.
The purpose is to prevent attribute name conflicts and ensure that each attribute name in the object is unique.
let s1 = Symbol('foo'); let s2 = Symbol('foo'); s1 === s2 // false
The Symbol type can have a string parameter representing a description of the Symbol instance. So two instances of the Symbol type with the same description are not equal.
let s = Symbol(); // 第一种写法 let a = {}; a[mySymbol] = 'Hello!'; // 第二种写法 let a = { [mySymbol]: 'Hello!' }; // 第三种写法 let a = {}; Object.defineProperty(a, mySymbol, { value: 'Hello!' }); // 以上写法都得到同样结果 a[mySymbol] // "Hello!"
It can be seen that when using the Symbol type as the attribute name, you must use []
. If not used, it represents the same string as the variable name as the attribute name.
Symbol is used as the attribute name. When traversing the object, the attribute will not appear in the
for...in
,for...of
loop. , will not be returned byObject.keys()
,Object.getOwnPropertyNames()
,JSON.stringify()
However, it is not a private property. There is a
Object.getOwnPropertySymbols()
method that can get all the Symbol property names of the specified object. This method returns an array whose members are all Symbol values used as property names of the current object.
Symbol.for("bar") === Symbol.for("bar") // true
Use the Symbol.for()
method, and the variables created with the same parameters will have the same value. Because the Symbol variable created using this method will register the parameters globally. The parameters of the variables created by Symbol()
will not be registered globally.
let s1 = Symbol.for("foo"); Symbol.keyFor(s1) // "foo" let s2 = Symbol("foo"); Symbol.keyFor(s2) // undefined
Use Symbol.keyFor()
The name of the globally registered parameter can be found in a variable.
Symbol.hasInstance
: When other objects use the instanceof
operator, they will use the internal method pointed to by the attribute name. .
Symbol.isConcatSpreadable
Symbol.species
Symbol.match
Symbol.replace
Symbol.search
Symbol.split
Symbol .iterator
Symbol.toPrimitive
Symbol.toStringTag
Symbol.unscopables
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of Is es6 symbol a basic type?. For more information, please follow other related articles on the PHP Chinese website!