Symbol js 易理解解读

21 阅读1分钟

symbol 是什么呢?

定义

  1. 是一个基础数据类型,用于表示唯一值,主要解决命名冲突问题
const s1 = Symbol('a');
const s2 = Symbol('a');
const obj = {
 [s1]: 'hello',
 [s2]: 'world'
};
console.log(obj[s1]); // "hello"console.log(obj[s2]); // "world"
s1 !== s2 
,这描述相同的两个 Symbol 值依然是不同的。

symbol 是基础数据类型,无法是用构造函数 new的方式去构建 ``

new Symbol()
VM2750:1 Uncaught TypeError: Symbol is not a constructor
    at new Symbol (<anonymous>)
    at <anonymous>:1:1

隐私安全,不会被遍历到

我们可以使用 Symbol 来创建这样一个“私有”属性。

1// 创建一个Symbol作为私有属性的键
2const counterKey = Symbol("counter");
3
4class Counter {
5  constructor(start = 0) {
6    // 使用Symbol作为属性名,存储计数值
7    this[counterKey] = start;
8  }
9
10  increment() {
11    this[counterKey]++;
12  }
13
14  decrement() {
15    this[counterKey]--;
16  }
17
18  // 提供一个公共方法来获取计数值,而不暴露实际的Symbol属性
19  getCount() {
20    return this[counterKey];
21  }
22}
23
24// 使用Counter类
25const myCounter = new Counter(10);
26console.log(myCounter.getCount()); // 输出: 10
27myCounter.increment();
28console.log(myCounter.getCount()); // 输出: 11
29
30// 尝试遍历或直接访问"私有"属性
31for (let key in myCounter) {
32  console.log(key); // counterKey 不会被遍历到
33}
34
35console.log(Object.keys(myCounter)); // 输出: [], counterKey 不在其中
36console.log(Object.getOwnPropertyNames(myCounter)); // 输出: [], 同样不在其中

在这个例子中,counterKey 是一个 Symbol 类型的值,它被用作 Counter 类实例中计数值的属性键。由于 Symbol 的特殊性质,当尝试使用 for...in 循环、Object.keys()Object.getOwnPropertyNames() 方法遍历对象的属性时,这个“私有”计数器属性不会被列出,从而实现了属性的隐藏和保护。