ES6学习——新的语法:Symbol API介绍

73 篇文章 23 订阅

关于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下通过测试

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值