Símbolo

Esta tradução está incompleta. Ajude atraduzir este artigo.

This is a new technology, part of the ECMAScript 2015 (ES6) standard.
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.

Sumário

O symbol é um tipo de dado único e imutável e pode ser usado como um identificador para propriedades de objeto. O objeto symbol e um empacotador de objetos implicitos para o símbolo tipo de dado primitivo.

Sintaxe

Symbol([descrição])

Parametros

descrição Optional
String opcional. Uma descrição de símbolo no qual pode ser usado para debugar mas não para acessar o próprio símbolo.

Descrição

Para criar um novo simbolo primitivo, simplesmente escreva Symbol() com uma string opçional para sua descrição:

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

O codigo acima cria três simbolos novos. Note que a função Symbol("foo") não faz a string "foo" ser um símbolo. Ela cria um novo simbolo a cada vez que é chamada:

Symbol("foo") === Symbol("foo"); // false

A sintaxe a seguir com o operador new vai resultar em um  TypeError:

var sym = new Symbol(); // TypeError

This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value. Creating an explicit wrapper object around primitive data types is no longer supported starting with ECMAScript 6. However, existing primitive wrapper objects like new Boolean, new String and new Number can still be created for legacy reasons.

And if you really want to create a Symbol wrapper object, you can use Object() function:

var sym = Symbol("foo");
typeof sym;     // "symbol" 
var symObj = Object(sym);
typeof symObj;  // "object"

Shared symbols in the global symbol registry

The above syntax using the Symbol() function will not create a global symbol that is available in your whole codebase. To create symbols available across files and in a global scope-like environment, use the methods Symbol.for() and Symbol.keyFor() to set and retrieve symbols from the global symbol registry.

Finding symbol properties on objects

The method Object.getOwnPropertySymbols() returns an array of symbols and lets you find symbol properties on a given object. Note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object.

Properties

Symbol.length
Length property whose value is 1.
Symbol.prototype
Represents the prototype for the Symbol constructor.

Well-known symbols

In addition to your own symbols, JavaScript has some built-in symbols which represent internal language behaviors which were not exposed to developers in ECMAScript 5 and before. These symbols can be accessed using the following properties:

Symbol.hasInstance
Specified as @@hasInstance. A method determining if a constructor object recognizes an object as its instance. Used by instanceof.
Symbol.isConcatSpreadable
Specified as @@isConcatSpreadable. A Boolean value indicating if an object should be flattened to its array elements. Used by Array.prototype.concat().
Symbol.isRegExp
Specified as @@isRegExp. A Boolean value indicating if an object may be used as a regular expression.
Symbol.iterator
Specified as @@iterator. A method returning the default iterator for an object. Used by for...of.
Symbol.toPrimitive
Specified as @@toPrimitive. A method converting an object to a primitive value.
Symbol.toStringTag
Specified as @@toStringTag. A string value used for the default description of an object. Used by Object.prototype.toString()
Symbol.unscopables
Specified as @@unscopables. An Array of string values that are property values. These are excluded from the with environment bindings of the associated objects.

Methods

Symbol.for(key)
Searches for existing symbols with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.
Symbol.keyFor(sym)
Retrieves a shared symbol key from the global symbol registry for the given symbol.

Symbol prototype

All Symbols inherit from Symbol.prototype.

Properties

Symbol.prototype.constructor
Returns the function that created an instance's prototype. This is the Symbol function by default.

Methods

Symbol.prototype.toSource()
Returns a string containing the source of the Symbol object. Overrides the Object.prototype.toSource() method.
Symbol.prototype.toString()
Returns a string of containing the description of the Symbol. Overrides the Object.prototype.toString() method.
Symbol.prototype.valueOf()
Returns the primitive value of the Symbol object. Overrides the Object.prototype.valueOf() method.
Symbol.prototype[@@toPrimitive]
Returns the primitive value of the Symbol object.

Examples

Using the typeof operator with symbols

The typeof operator can help you to identify symbols.

typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'

Symbol type conversions

Some things to note when working with type conversion of symbols.

  • When trying to convert a symbol to a number, a TypeError will be thrown
    (e.g. +sym or sym | 0).
  • When using loose equality, Object(sym) == sym returns true.
  • Symbol("foo") + "bar" throws a TypeError (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example.
  • The "safer" String(sym) conversion works like a call to Symbol.prototype.toString() with symbols, but note that new String(sym) will throw.

Symbols and for...in iteration

Symbols are not visible in for...in iterations. In addition, Object.getOwnPropertyNames() will not return symbol object properties, however, you can use Object.getOwnPropertySymbols() to get these.

var obj = {};

obj[Symbol("a")] = "a";
obj[Symbol.for("b")] = "b";
obj["c"] = "c";
obj.d = "d";

for (var i in obj) {
   console.log(i); // logs "c" and "d"
}

Symbols and JSON.stringify()

Symbol-keyed properties will be completely ignored when using JSON.stringify():

JSON.stringify({[Symbol("foo")]: "foo"});                 
// '{}'

For more details, see JSON.stringify().

Symbol wrapper objects as property keys

When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:

var sym = Symbol("foo");
var obj = {[sym]: 1};
obj[sym];            // 1
obj[Object(sym)];    // still 1

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Symbol' in that specification.
Standard Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 38 36.0 (36.0) Não suportado 25 Não suportado
Symbol.iterator (@@iterator) 38 36.0 (36.0) Não suportado 25 Não suportado
Symbol.unscopables (@@unscopables) 38 Não suportado Não suportado 25
Não suportado
Other well-known symbols Não suportado Não suportado Não suportado Não suportado Não suportado
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support Não suportado 38 36.0 (36.0) Não suportado 25 Não suportado
Symbol.iterator (@@iterator) Não suportado 38 36.0 (36.0) Não suportado 25 Não suportado
Symbol.unscopables (@@unscopables)
Não suportado 38 ? Não suportado 25 Não suportado
Other well-known symbols Não suportado Não suportado Não suportado Não suportado Não suportado Não suportado

See also

Etiquetas do documento e colaboradores

 Colaboradores desta página: Grohden, raduq, astesio, AlanCezarAraujo
 Última atualização por: Grohden,