初识Symbol
- 什么是Symbol?
- 可以理解它为一个标识,一般情况下用来解决重名问题。
let hd = Symbol('hello,dust.')
let edu = Symbol('good afternoon')
console.log(hd == edu) //false
- 一个Symbol要反复使用可以用Symbol.for定义
let a = Symbol.for('good morning')
let b = Symbol.for('good morning')
console.log(a) //Symbol(good morning)
console.log(a == b) //true
console.log(Symbol.keyFor(a)) //good morning
- 当我们要从一个对象中取值时:
- 假设这个班上有两个李四,我们要把学生名字作为key,怎么办?
- 一般情况:
let user1 = '李四'
let user2 = '李四'
let grade = {
user1: { js: 100, css: 89 },
user2: { js: 100, css: 89 },
}
console.log(grade) //{ user1: { js: 100, css: 89 }, user2: { js: 100, css: 89 } }
let grade2 = {
[user1]: { js: 100, css: 89 },
[user2]: { js: 70, css: 55 },
}
console.log(grade2) //{ '李四': { js: 70, css: 55 } }
- 用了Symbol的情况:
let user1 = {
name: '李四',
key: Symbol(),
}
let user2 = {
name: '李四',
key: Symbol(),
}
let grade = {
[user1.key]: { js: 100, css: 89 },
[user2.key]: { js: 35, css: 55 },
}
console.log(grade)
//{ [Symbol()]: { js: 100, css: 89 }, [Symbol()]: { js: 35, css: 55 } }
console.log(grade[user1.key]) //{ js: 100, css: 89 }
- Symbol就相当于生成一个永远不会重复的字符串
let user = {
name: 'cat',
desc: '用户资料',
key: Symbol('user'),
}
let cart = {
name: 'apple',
desc: '购物车',
key: Symbol('购物车数据'),
}
Cache.set(user.key, user)
Cache.set(cart.key, cart)
console.log(Cache.get(cart.key))
//{ name: 'apple', desc: '购物车', key: Symbol(购物车数据) }
Symbol在类中的作用
class Cache {
static data = {}
static set(name, value) {
return (this.data[name] = value)
}
static get(name) {
return this.data[name]
}
}
Cache.set('hello', 'dust')
console.log(Cache.get('hello')) //dust
另一个例子:
let site = Symbol('this is a Symbol')
class User {
constructor(name) {
this.name = name
this[site] = 'dust'
}
getName() {
return `${this[site]} ${this.name}`
}
}
let v = new User('lisa')
console.log(v.getName()) //dust lisa
for (const key in v) {
console.log(key) //name
}
几种取值的方式
let symbol = Symbol('这是一个Symbol类型')
let hd = {
name: 'dust',
[symbol]: 'hello',
}
for (const key of Object.keys(hd)) {
console.log(key) //name
}
for (const key of Object.getOwnPropertySymbols(hd)) {
console.log(key) //Symbol(这是一个Symbol类型)
}
for (const key of Reflect.ownKeys(hd)) {
console.log(key)
/*
name
Symbol(这是一个Symbol类型)
*/
}