ES6 Symbol类型

创建 Symbol 类型数据

  1. 通过函数创建。

    1
    2
    3
    4
    let s1 = Symbol();
    let s2 = Symbol('张三');
    let s3 = Symbol('张三');
    console.log(s2 === s3); // false
  2. 通过对象创建。

    1
    2
    3
    4
    let s1 = Symbol.for();
    let s2 = Symbol.for('张三');
    let s3 = Symbol.for('张三');
    console.log(s2 === s3); // true

通过 Symbol 给对象添加方法

1
2
3
4
5
6
7
let stu = {
name: '张三'
}
stu[Symbol('run')] = () => {
console.log('跑步');
}
console.log(stu);