What is the “symbol” primitive data type in JavaScript [duplicate]

允我心安 提交于 2019-11-28 10:12:37

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.

Example without symbols:

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!