0%

symbol

ES6 Symbol

表示一个独一无二的值

  1. const sym = Symbol() 不需要 new
  2. unique
    1
    2
    3
    const s1 = Symbol('tan')
    const s2 = Symbol('tan')
    console.log(s1 === s2); // error
  3. 不能使用运算符
    1
    2
    3
    const s3 = Symbol(100)
    console.log(s3 + 200); // TS2365: Operator '+' cannot be applied to types 'unique symbol' and 'number'.
    // 不能使用运算符 或 + 拼接
  4. toString()
    1
    console.log(s3.toString() + 200);      // toString() + 拼接   "Symbol(100)200"

作为对象的属性

1
2
3
4
5
6
7
8
let s4 = Symbol('name')
const obj = {
[s4]: 's4'
}
console.log(obj); // {Symbol(name): 'volvo s4'}
console.log(obj.s4); // error
obj[s4] = 'volvo s60'
console.log(obj); // {Symbol(name): 's60'}
  • 不能通过对象形式访问 Symbol 类型的属性:obj.name || obj.s4

  • 只能 obj[s4] 访问

  • 遍历:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    let s4 = Symbol('name')
    const obj = {
    [s4]: 's4',
    a: 'aaa',
    b: '1231'
    }
    for (let key in obj) {
    console.log(key); // a b Symbol 类型不会被遍历出来
    }
    console.log(Object.keys(obj)) // ['a', 'b'] 同样不会
    console.log(Object.getOwnPropertyNames(obj)) // ['a', 'b'] 同样不会
    console.log(JSON.stringify(obj)) // {"a":"aaa","b":"1231"} 同样不会


    console.log(Object.getOwnPropertySymbols(obj)) // [Symbol(name)] 只返回 symbol 类型的属性名 key

    console.log(Reflect.ownKeys(obj)) // ['a', 'b', Symbol(name)] 返回所有

静态方法

for()

返回一个 Symbol 类型的值

1
2
3
4
5
6
const s7 = Symbol.for('s5')
// 再次使用 for 方法创建 symbol 的时候,会先判断 全局是否存在使用 string s5 的值,有则直接返回,没有则创建
const s8 = Symbol.for('s5')
const s9 = Symbol.for('s60')
console.log(s7 === s8); // true
console.log(s8 === s9); // false

keyFor()

  • 返回一个 Symbol 类型的值的 索引
  • 只接受 Symbol.for() 方法创建的值
  • 对于 Symbol() 则返回 undefined
1
2
3
4
5
6
let s4 = Symbol('name')
const s8 = Symbol.for('haha')
const s9 = Symbol.keyFor(s8)
const s10 = Symbol.keyFor(s4)
console.log(s9); // haha 只接受 Symbol.for 方法创建的值
console.log(s10); // undefined

内置属性

  1. Symbol.hasInstance 返回使用 instanceof 判断 symbol 类型的原始对象
  2. Symbol.isConcatSpreadable
-------------本文结束感谢您的阅读-------------