Edge JsRT: Symbols

In ES6, the new Symbol language feature allows people (especially hosts) to extend JavaScript objects without polluting their property namespaces. So you can add, say, a Boolean property to an object and instead of giving that property a name like “isCounted,” you can instead create a Symbol (“var isCountedSymbol = Symbol();”) and then use that symbol as the property name (“obj[isCountedSymbol] = true;”). Then people iterating over the property names on that object won’t see your symbol and won’t get tripped up. And you can be fairly sure no one else is going to accidentally stomp on your property or collide with it.

(You can read more about the language feature here.)

Symbols are values, so JsGetValueType now has a new type it will return, JsSymbol. You can create a new Symbol through JsRT using JsCreateSymbol. You can get a property ID from a symbol using JsGetPropertyIdFromSymbol, and you can get the symbol from a property ID (assuming it is a property ID created from a symbol) using JsGetSymbolFromPropertyId. JsGetPropertyIdType will tell you whether a property ID was created using a symbol or a property name. You can use GetOwnPropertySymbols to get any properties on an object that are indexed using symbols (as they won’t show up in GetOwnPropertyNames).

You should also follow me on Twitter here.

Leave a Reply

Your email address will not be published. Required fields are marked *