Symbol (SA00)
JavaScript Symbols: JavaScript Symbols are primarily intended as unique property keys. They are used as data, not metadata. While well-known symbols like Symbol.iterator allow customizing certain built-in behaviors, they are still used as property keys on objects. They directly participate in the object's behavior during runtime.:
- • Symbol.for() and Symbol.keyFor() (Static Methods):
- ◦ These are static methods because they operate on the global Symbol registry. Symbol.for() registers or retrieves a symbol globally, and Symbol.keyFor() retrieves the key associated with a globally registered symbol. These operations inherently involve a global registry, and individual Symbol instances aren't directly involved. They are accessed via the Symbol object itself.
- • Symbol.toPrimitive (Well-known Symbol, Used as Instance Property):
- ◦ Symbol.toPrimitive is a well-known symbol, not a method or static property. It is meant to be used as a property key on object instances. The value of this property should be a method that JavaScript can call to convert an object to a primitive value (number, string, or boolean). So, Symbol.toPrimitive itself is not a method, but it is used to identify the method on an object that handles primitive conversion. It's a way for you to customize how your objects are coerced into primitive values.
- • Symbol.iterator and other Well-known Symbols (Used as Instance Properties):
- ◦ Symbol.iterator, like Symbol.toPrimitive, is a well-known symbol and serves as an instance property key. Its value on an object is the method that JavaScript uses to iterate over that object (e.g., in a for...of loop). This makes iteration a customizable behavior. Other well-known symbols also provide hooks for customizing various aspects of how objects behave in the language.
Key Differences and Clarifications
- • Static vs. Instance: Static members (Symbol.for, Symbol.keyFor) are associated with the Symbol class itself. Instance members (Symbol.iterator, Symbol.toPrimitive when used as a property) are associated with individual objects.
- • Symbol.toPrimitive is not a method: It's a Symbol instance that, by convention, is used as a key to define a method on your objects that should handle type coercion. It's a way to define how your objects should be converted to primitives, not the conversion method itself.
- • Well-known Symbols are for Customization: Symbol.iterator, Symbol.toPrimitive, and others provide standard "hooks" for you to customize fundamental behaviors (iteration, type coercion) for your own objects.
It's used when you want an object to be asynchronously iterable (usable with for await...of loops). 1 2 3
Symbol context:
ES6 context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/JavascriptES6/SY00.htm
|
|