Symbol
ECMAScript 6 symbols began as a way to create private object members, a feature JavaScript developers have long wanted.
Symbols are actually a new kind of primitive value, joining strings, numbers, booleans, null
, and undefined
. They are unique among JavaScript primitives in that they do not have a literal form. The ECMAScript 6 standard uses a special notation to indicate symbols, prefixing the identifier with @@
, such as @@create
. This book uses this same convention for ease of understanding.
- Define a Symbol
person
var firstName = Symbol("first name");
var person = {};
person[firstName] = "Nicholas";
console.log("first name" in person); // false
console.log(person[firstName]); // "Nicholas"
console.log(firstName); // "Symbol(first name)" use for debug
console.log(typeof firstName); // "symbol"
// The Advanced Usage
var firstName = Symbol("first name");
var person = {
[firstName]: "Nicholas"
};
// make the property read only
Object.defineProperty(person, firstName, { writable: false });
var lastName = Symbol("last name");
Object.defineProperties(person, {
[lastName]: { value: "Zakas", writable: false }
});
console.log(person[firstName]); // "Nicholas"
console.log(person[lastName]); // "Zakas"
Reuse Symbol
Symbol.for()
Symbol.keyFor()
var uid = Symbol.for("uid");
var object = { [uid]: "12345" };
console.log(object[uid]); // "12345"
console.log(uid); // "Symbol(uid)"
var uid2 = Symbol.for("uid");
console.log(uid === uid2); // true
console.log(object[uid2]); // "12345"
console.log(uid2); // "Symbol(uid)"
Finding Object Symbols
- with method:
Object.getOwnPropertySymbols(obj)
- with method:
Well-known Symbols: represent common behaviors in JavaScript that were previously considered internal-only operations.
- Overwriting a method defined with a well-known symbol changes an ordinary object to an exotic object because this changes some internal default behavior.