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
personvar firstName = Symbol("first name");var person = {};person[firstName] = "Nicholas";console.log("first name" in person); // falseconsole.log(person[firstName]); // "Nicholas"console.log(firstName); // "Symbol(first name)" use for debugconsole.log(typeof firstName); // "symbol"// The Advanced Usagevar firstName = Symbol("first name");var person = {[firstName]: "Nicholas"};// make the property read onlyObject.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); // trueconsole.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.
