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
  1. person
  2. var firstName = Symbol("first name");
  3. var person = {};
  4. person[firstName] = "Nicholas";
  5. console.log("first name" in person); // false
  6. console.log(person[firstName]); // "Nicholas"
  7. console.log(firstName); // "Symbol(first name)" use for debug
  8. console.log(typeof firstName); // "symbol"
  9. // The Advanced Usage
  10. var firstName = Symbol("first name");
  11. var person = {
  12. [firstName]: "Nicholas"
  13. };
  14. // make the property read only
  15. Object.defineProperty(person, firstName, { writable: false });
  16. var lastName = Symbol("last name");
  17. Object.defineProperties(person, {
  18. [lastName]: { value: "Zakas", writable: false }
  19. });
  20. console.log(person[firstName]); // "Nicholas"
  21. console.log(person[lastName]); // "Zakas"
  • Reuse Symbol

    • Symbol.for()
    • Symbol.keyFor()
  1. var uid = Symbol.for("uid");
  2. var object = { [uid]: "12345" };
  3. console.log(object[uid]); // "12345"
  4. console.log(uid); // "Symbol(uid)"
  5. var uid2 = Symbol.for("uid");
  6. console.log(uid === uid2); // true
  7. console.log(object[uid2]); // "12345"
  8. console.log(uid2); // "Symbol(uid)"
  • Finding Object Symbols

    • with method: Object.getOwnPropertySymbols(obj)
  • 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.