ES6 Symbols

ES6 Symbols

Symbols are primitive types introduced in ES6.

Symbols are used to generate a unique value for an object. Symbols are created as wrapper around values and are generally used to provide object immutability through its uniqueness and a tint of encapsulation by hiding the properties of an object to other scopes of code.

A Symbol is created using the Symbol() function (not to be confused with the constructor function).

const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");        

The above code creates three unique symbols. The type of each Symbol in JavaScript is "symbol".

Symbols are managed in a hypothetical concept known as Symbol Global Registry.

The method Symbol.for(token) takes a string key and returns a symbol value from the registry.

const symbol1 = Symbol.for('foo');

console.log(symbol1.toString());

// "Symbol(foo)"        

Similarly Symbol.keyFor(symbol) takes a symbol value and returns the string key corresponding to it.

const sym= Symbol.for('foo');

console.log(Symbol.keyFor(sym));
//  "foo"        

Symbols allow us to encapsulate properties of an object, that cant be accessed or modified in other parts of the code.

let id = Symbol("id");

let user = {
  name: "John",
  [id]: 123 // unique, can't be overwritten
};        

Symbol polyfill can be found here : Symbol Polyfill

More information on Symbol and browser compatibility can be found here : ES6 Symbol


#javascript #symbol #es6


要查看或添加评论,请登录

社区洞察

其他会员也浏览了