关于Symbol API的描述在规范的19.4节中,有兴趣的自己去看。Symbol的API并不多如果不算well known的symbols,一个一个过一下:
1)Symbol函数
When Symbol is called with optional argument description, the following steps are taken:
1. If NewTarget is not undefined, throw a TypeError exception.
2. If description is undefined, let descString be undefined.
3. Else, let descString be ToString(description).
4. ReturnIfAbrupt(descString).
5. Return a new unique Symbol value whose [[Description]] value is descString.
例子:
Symbol();
Symbol("desc");
Symbol(9);
Symbol({key:"value"})
2)toString方法,toString方法内部调用的是SymbolDescriptiveString ( sym ),我们直接看这个方法定义
When the abstract operation SymbolDescriptiveString is called with argument sym, the following steps are taken:1. Assert: Type(sym) is Symbol.2. Let desc be sym’s [[Description]] value.3. If desc is undefined, let desc be the empty string.4. Assert: Type(desc) is String.5. Return the result of concatenating the strings "Symbol(", desc, and ")".
例子:
Symbol().toString();//"Symbol()"
Symbol("desc").toString();//"Symbol(desc)"
Symbol(9).toString();//"Symbol(9)"
Symbol({key:"value"}).toString();//"Symbol([object Object])"
3)valueOf方法,可以认为valueOf方法返回的就是symbol本身
The following steps are taken:
1. Let s be the this value.
2. If Type(s) is Symbol, return s.
3. If Type(s) is not Object, throw a TypeError exception.
4. If s does not have a [[SymbolData]] internal slot, throw a TypeError exception.
5. Return the value of s’s [[SymbolData]] internal slot.
例子:
var sym = Symbol();
sym === sym.valueOf();//true
4)for,keyFor方法,这两个方法比较重要。for就是在全局范围内创建一个单例的symbol对象,keyFor方法则是在全局范围内查找symbol实例
Symbol.for:
1. Let stringKey be ToString(key).
2. ReturnIfAbrupt(stringKey).
3. For each element e of the GlobalSymbolRegistry List,
a. If SameValue(e.[[key]], stringKey) is true, return e.[[symbol]].
4. Assert: GlobalSymbolRegistry does not currently contain an entry for stringKey.
5. Let newSymbol be a new unique Symbol value whose [[Description]] value is stringKey.
6. Append the record { [[key]]: stringKey, [[symbol]]: newSymbol } to the GlobalSymbolRegistry List.
7. Return newSymbol.
Symbol.keyFor:
1. If Type(sym) is not Symbol, throw a TypeError exception.
2. For each element e of the GlobalSymbolRegistry List (see 19.4.2.1),
a. If SameValue(e.[[symbol]], sym) is true, return e.[[key]].
3. Assert: GlobalSymbolRegistry does not currently contain an entry for sym.
4. Return undefined.
看个例子:
var s = Symbol.for( "something cool" );
var desc = Symbol.keyFor( s );
console.log( desc ); // "something cool"
var s2 = Symbol.for( desc );
s2 === s; // true
*以上全部代码在Firefox 43下通过测试