Symbol is a primitive data type of JavaScript, along with string, number, boolean, null and undefined.
Symbol是JavaScript的原始数据类型,包括string , number ,boolean,null和undefined。
It was introduced in ECMAScript 2015, so just a few years ago.
它是几年前在ECMAScript 2015中引入的。
It’s a very peculiar data type. Once you create a symbol, its value is kept private and for internal use.
这是一种非常特殊的数据类型。 创建符号后,其值将保持私有状态并仅供内部使用。
All that remains after the creation is the symbol reference.
创建后剩下的所有内容就是符号引用。
You create a symbol by calling the Symbol()
global factory function:
您可以通过调用Symbol()
全局工厂函数来创建符号:
const mySymbol = Symbol()
Every time you invoke Symbol()
we get a new and unique symbol, guaranteed to be different from all other symbols:
每次调用Symbol()
我们都会得到一个新的唯一符号,该符号保证与所有其他符号都不同:
Symbol() === Symbol() //false
You can pass a parameter to Symbol()
, and that is used as the symbol description, useful just for debugging purposes:
您可以将参数传递给Symbol()
,并将其用作符号描述 ,仅用于调试目的:
console.log(Symbol()) //Symbol()
console.log(Symbol('Some Test')) //Symbol(Some Test)
Symbols are often used to identify object properties.
符号通常用于标识对象属性。
Often to avoid name clashing between properties, since no symbol is equal to another.
通常避免属性之间的名称冲突,因为没有符号等于另一个。
Or to add properties that the user cannot overwrite, intentionally or without realizing.
或者添加有意或无意识的用户无法覆盖的属性。
Examples:
例子:
const NAME = Symbol()
const person = {
[NAME]: 'Flavio'
}
person[NAME] //'Flavio'
const RUN = Symbol()
person[RUN] = () => 'Person is running'
console.log(person[RUN]()) //'Person is running'
Symbols are not enumerated, which means that they do not get included in a for..of
or for..in
loop ran upon an object.
不枚举符号,这意味着它们不会包含在对象上的for..of
或for..in
循环中 。
Symbols are not part of the Object.keys()
or Object.getOwnPropertyNames()
result.
符号不是Object.keys()
或Object.getOwnPropertyNames()
结果的一部分。
You can access all the symbols assigned to an object using the Object.getOwnPropertySymbols()
method.
您可以使用Object.getOwnPropertySymbols()
方法访问分配给对象的所有符号。