WeakMap better than Private Symbols? (was: direct_proxies "problem")
Herby Vojčík
herby at mailbox.sk
Thu Jan 10 08:32:41 PST 2013
Nathan Wall wrote:
> // ES6 Symbols
>
> // Forgive me for not knowing what the current
> // correct syntax is for creating a symbol:
> let timestamp = new Symbol();
>
> class SimpleDate {
>
> construct(time) {
> this.setTime(time);
> }
>
> setTime(time) {
> this[timestamp] = +time;
> }
>
> getTime() {
> return this[timestamp];
> }
>
> }
>
>
> // ES6 WeakMap
>
> let timeMap = new WeakMap(),
> // Store WeakMap methods to maintain integrity of the internal state.
> WeakMapGet = Function.prototype.call.bind(WeakMap.prototype.get),
> WeakMapSet = Function.prototype.call.bind(WeakMap.prototype.set);
>
> class SimpleDate {
>
> construct(time) {
> this.setTime(time);
> }
>
> setTime(time) {
> WeakMapSet(timeMap, this, +time);
> }
>
> getTime() {
> return WeakMapGet(timeMap, this);
> }
>
> }
>
> AFAIK the two ES6 implementations above should function the same, except when (1) a Proxy uses a SimpleDate as the target and (2) a SimpleDate is frozen.
>
> In the case of (1), the implementation using a private symbol will have internal accesses to the `timestamp` symbol exposed through the unknownPrivateSymbol trap.
>
> In the case of (2), the implementation using a private symbol will fail on a call to `setTime` when the object is frozen (I think).
IIRC, private symbols are exempt from freezing.
Herby
More information about the es-discuss
mailing list