1、Symbols 介绍
- ES6 提供 Symbols 类型,内建原生类型
- Symbols l类型的值是通过Symbol构造函数创建的
- Symbols 是不可改变且唯一的
- 像字符串一样,Symbols 也可以被用做对象属性的键
2、示例
2.1 Symbol 值唯一
let sym1 = Symbol();
let sym2 = Symbol('key');
let sym3 = Symbol('key');
console.log(sym1, sym2, sym3)
console.log(sym2 == sym3)
2.2 Symbol 作为对象的属性 key
let s = Symbol()
let t = 'abc'
let a = {
[s]:'xyz',
t:'ttt',
[t]:'ooo'
}
console.log(a)
console.log(a[s])
a[s] = 2000
console.log(a[s])
Info: Start process (下午7:01:31)
{ t: 'ttt', abc: 'ooo', [Symbol()]: 'xyz' }
xyz
2000
Info: End process (下午7:01:31)
2.3 构建常量
var COLOR_RED = 'RED';
var COLOR_YELLOW = 'YELLOW';
var COLOR_BLACK = 'BLACK';
const COLOR_RED = Symbol();
const COLOR_YELLOW = Symbol();
const COLOR_BLACK = Symbol();
2.4 “表达式的值,表达式的值”
2.4.1 示例
let s = Symbol('key')
let a = 1000
let obj = {
a,
b:'abc',
s
}
console.log(obj)
Info: Start process (下午10:36:23)
{ a: 1000, b: 'abc', s: Symbol(key) }
Info: End process (下午10:36:23)
2.4.2 示例
let s = Symbol('key')
let a = 1000
let obj = {
a,
b:'abc',
s
}
Info: Start process (下午10:38:32)
{ a: 1000, b: 'abc', s: Symbol(key) }
Info: End process (下午10:38:33)
2.4.3 示例
let s = Symbol('key')
let a = 1000
let obj = {
a,
b:'abc',
s:s
}
console.log(obj)
Info: Start process (下午10:40:05)
{ a: 1000, b: 'abc', s: Symbol(key) }
Info: End process (下午10:40:06)
2.4.4 示例
let s = Symbol('key')
let a = 1000
let obj = {
a,
b:'abc',
[s]:2000
}
console.log(obj)
Info: Start process (下午10:41:13)
{ a: 1000, b: 'abc', [Symbol(key)]: 2000 }
Info: End process (下午10:41:13)
2.4.5 示例
let s = Symbol('key')
let a = 1000
let obj = {
a,
b:'abc',
[s]:2000
}
console.log(obj)
for (x in obj)
console.log(x)
console.log('a' in obj)
console.log(s in obj)
console.log(obj[s])
obj[s] = 3000
console.log(obj[s])
Info: Start process (下午10:44:29)
{ a: 1000, b: 'abc', [Symbol(key)]: 2000 }
a
b
true
true
2000
3000
Info: End process (下午10:44:29)