JavaScript符号

Symbol is a primitive data type of JavaScript, along with string, number, boolean, null and undefined.

Symbol是JavaScript的原始数据类型,包括stringnumber ,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..offor..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()方法访问分配给对象的所有符号。

翻译自: https://flaviocopes.com/javascript-symbols/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值