TIL coding
  • Initial page
  • 排版
  • Flexbox
  • Grid
  • jQuery
  • Untitled
  • JavaScript
    • An Introduction to JavaScript
    • Hello, world!
    • Code structure
    • The modern mode, "use strict"
    • Variables
    • Data types
    • Type Conversions
    • Operators
    • Comparisons
    • Interaction: alert, prompt, confirm
    • Conditional operators: if, '?'
    • Logical operators
    • Loops: while and for
    • The "switch" statement
    • Functions
    • Function expressions and arrows
    • JavaScript specials
    • Comments
    • Ninja code
    • Automated testing with mocha
    • Polyfills
    • Objects
    • Garbage collection
    • Symbol type
    • Object methods, "this"
    • Object to primitive conversion
    • Constructor, operator "new"
    • Methods of primitives
    • Numbers
    • Strings
    • Arrays
    • Array methods
    • Iterables
    • Map, Set, WeakMap and WeakSet
    • Object.keys, values, entries
    • Destructuring assignment
    • Date and time
    • JSON methods, toJSON
    • Recursion and stack
    • Rest parameters and spread operator
    • Closure
    • The old "var"
    • Global object
    • Function object, NFE
    • The "new Function" syntax
    • Scheduling: setTimeout and setInterval
    • Decorators and forwarding, call/apply
    • Function binding
    • Currying and partials
    • Arrow functions revisited
    • Property flags and descriptors
    • Property getters and setters
    • Prototypal inheritance
    • F.prototype
    • Native prototypes
    • Prototype methods, objects without __proto__
    • The “class” syntax
    • Class inheritance
    • Static properties and methods
    • Private and protected properties and methods
    • Extending built-in classes
    • Class checking: "instanceof"
    • Mixins
    • Error handling, "try..catch"
    • Custom errors, extending Error
    • Introduction: callbacks
    • Promise
    • Promises chaining
    • Error handling with promises
    • Promise API
  • Bootstrap
    • Navbar
Powered by GitBook
On this page
  • Symbols
  • Symbols don’t auto-convert to a string
  • “Hidden” properties
  • Symbols in a literal
  • Symbols are skipped by for…in
  • Global symbols
  • Symbol.keyFor
  • System symbols

Was this helpful?

  1. JavaScript

Symbol type

物件 key 只能是 string or symbol 2 種類型

Symbols

symbol 代表唯一的值。

// id is a new symbol
let id = Symbol();

// id is a symbol with the description "id" for debug purpose
let id = Symbol("id");

// same description but different value
let id1 = Symbol("id");
let id2 = Symbol("id");

alert(id1 == id2); // false

Symbols don’t auto-convert to a string

​JavaScript 大多數的值可以自動轉換成 string 但 symbol 無法自動轉換。

let id = Symbol("id");
alert(id); // TypeError: Cannot convert a Symbol value to a string

// convert to string
let id = Symbol("id");
alert(id.toString()); // Symbol(id), now it works

// only get description
let id = Symbol("id");
alert(id.description); // id

“Hidden” properties

symbol 可以為物件創造隱藏的屬性,程式碼的其他部份不容易取得或改寫。

let user = { name: "John" };
let id = Symbol("id");

user[id] = "ID Value";
alert( user[id] ); // we can access the data using the symbol as the key

// useing string would be a conflict 
let user = { name: "John" };

// our script uses "id" property
user.id = "ID Value";

// ...if later another script the uses "id" for its purposes...

user.id = "Their id value"
// boom! overwritten! it did not mean to harm the colleague, but did it!

Symbols in a literal

使用 symbol 作為 key 值,要加上 [ ] 因為它是一個變數。

let id = Symbol("id");

let user = {
  name: "John",
  [id]: 123 // not just "id: 123"
};

Symbols are skipped by for…in

symbol 不算在物件迴圈內 for ( in )。

let id = Symbol("id");
let user = {
  name: "John",
  age: 30,
  [id]: 123
};

for (let key in user) alert(key); // name, age (no symbols)

// the direct access by the symbol works
alert( "Direct: " + user[id] );

// Object.assign() 會複製 symbol
let id = Symbol("id");
let user = {
  [id]: 123
};

let clone = Object.assign({}, user);

alert( clone[id] ); // 123

// other type of key convert to string
let obj = {
  0: "test" // same as "0": "test"
};

// both alerts access the same property (the number 0 is converted to string "0")
alert( obj["0"] ); // test
alert( obj[0] ); // test (same property)

Global symbols

symbol 通常是唯一的值,但如果想要同樣的 symbol 可以用 Symbol.for(key) 設定全域 symbol registry。

// read from the global registry
let id = Symbol.for("id"); // if the symbol did not exist, it is created

// read it again
let idAgain = Symbol.for("id");

// the same symbol
alert( id === idAgain ); // true

Symbol.keyFor

Symbol.keyFor(sym) 返回全域 symbol 的 key名稱。

let sym = Symbol.for("name");
let sym2 = Symbol.for("id");

// get name from symbol
alert( Symbol.keyFor(sym) ); // name
alert( Symbol.keyFor(sym2) ); // id

// 只能使用在全域的 symbol
alert( Symbol.keyFor(Symbol.for("name")) ); // name, global symbol
alert( Symbol.keyFor(Symbol("name2")) ); // undefined, the argument isn't a global symbol

System symbols

  • Symbol.hasInstance

  • Symbol.isConcatSpreadable

  • Symbol.iterator

  • Symbol.toPrimitive

  • …and so on.

PreviousGarbage collectionNextObject methods, "this"

Last updated 5 years ago

Was this helpful?