什么是“符号”? JavaScript中的原始数据类型 [英] What is the "symbol" primitive data type in JavaScript
问题描述
新的原始类型带有符号类型的ES6。简短定义说:
The new primitive type comes with ES6 which is Symbol type.The short definition says :
符号是一种唯一且不可变的数据类型,可用作对象属性的标识符。符号对象是符号原始数据类型的隐式对象包装器。
A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol object is an implicit object wrapper for the symbol primitive data type.
我做了一些研究,但我无法理解为什么我们需要这种原始类型呢?
I did some research but I cannot understand why we need this primitive type exactly?
感谢您的回答。
推荐答案
这种原始类型对于称为私人和/或唯一密钥。
This primitive type is useful for so-called "private" and/or "unique" keys.
使用符号,您知道没有其他人不共享此实例 (而不是字符串)将无法在地图上设置特定属性。
Using a symbol, you know no one else who doesn't share this instance (instead of the string) will not be able to set a specific property on a map.
没有符号的示例:
var map = {};
setProp(map);
setProp2(map);
function setProp(map) {
map.prop = "hey";
}
function setProp2(map) {
map.prop = "hey, version 2";
}
在这种情况下,第二个函数调用将覆盖第一个函数中的值。
In this case, the 2nd function call will override the value in the first one.
然而,对于符号,我们使用实例本身而不是仅仅使用字符串 prop
:
However, with symbols, instead of just using "the string prop
", we use the instance itself:
var map = {};
var symbol1 = Symbol("prop");
var symbol2 = Symbol("prop"); // same name, different instance – so it's a different symbol!
map[symbol1] = 1;
map[symbol2] = 2; // doesn't override the previous symbol's value
console.log(map[symbol1] + map[symbol2]); // logs 3
这篇关于什么是“符号”? JavaScript中的原始数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!