• Symbol 是唯一的
  • 无法使用 for 遍历
  • 获取 Symbol
  • Symbol.for
  • Symbol.keyFor
  • 重写 JS 语法的默认行为,跟 C++ 的操作符重载差不多的意思

Symbol 是唯一的

var foo1 = Symbol('foo');
var foo2 = Symbol('foo');
var object = {
    [foo1]: 1,
    [foo2]: 2,
};
console.log(object[foo1]); // 1
console.log(object[foo2]); // 2
console.log(foo1 === foo2); // false

无法使用 for 遍历

for infor of 遍历

let arr = ["a","b"];
for (a in arr) {
  console.log(a);//1,2
}

for (a of arr) {
  console.log(a);//a,b
}

对含有 Symbol 对象遍历

var foo = Symbol('foo');
var object = {
  [foo]: 'foo-value',
  key: 'value'
};

for (var k in object) {
  console.log(`${k}:${object[k]}`);
  // key:value
}

// Uncaught TypeError: object[Symbol.iterator] is not a function
for (var k of object) {
  console.log(`${k}:${object[k]}`);
}

获取Symbol

var fooSym = Symbol('foo');
var myObj = {
  foo: 'bar',
  [fooSym]: 'baz'
};
console.log(Object.keys(myObj)); // -> [ 'foo' ]
console.log(Object.getOwnPropertyNames(myObj)); // -> [ 'foo' ]
console.log(Object.getOwnPropertySymbols(myObj)); // -> [ Symbol(foo) ]

Symbol.for

Symbol.for('foo') === Symbol.for('foo') // true
Symbol('foo') === Symbol('foo') // false

Symbol.keyFor

var localFooSymbol = Symbol('foo');
var globalFooSymbol = Symbol.for('foo');

console.log(Symbol.keyFor(localFooSymbol) === undefined); // true
console.log(Symbol.keyFor(globalFooSymbol) === 'foo'); // true
console.log(Symbol.for(Symbol.keyFor(globalFooSymbol)) === Symbol.for('foo')); // true

重写 JS 语法的默认行为

  • Symbol.hasInstance: instanceof
  • Symbol.iterator: for of
  • Symbol.isConcatSpreadable: concat
  • Symbol.unscopables
  • Symbol.match
  • Symbol.replace
  • Symbol.search
  • Symbol.split
  • Symbol.species
  • Symbol.toPrimitive
  • Symbol.toStringTag

Reference