taquaki-satwo
11/27/2017 - 3:15 PM

Symbolオブジェクト

JS-Symbolオブジェクト

const SECRET = Symbol();

class MyClazz {
  constructor(secret) {
    this.data1 = 1;
    this.data2 = 2;
    // symbolを使いプロパティを隠蔽する
    this[SECRET] = secret;
  }

  checkSecret(secret) {
    return this[SECRET] === secret;
  }
}

let c = new MyClazz(1234);

// メソッド越しにはアクセスできる
console.log(c.checkSecret(1234)); // -> true
console.log(c.secret); // -> undefined
console.log(Object.keys(c)); // -> ["data1", "data2"]

// Object.getOwnPropertySymbolsメソッドでアクセスできる
console.log(c[Object.getOwnPropertySymbols(c)[0]]) // -> 1234

// 組み込みコンストラクタの安全な拡張
Array.prototype[Symbol.for('shuffle')] = function() {
  const a = this;
  let m = a.length, t, i;
  while(m) {
    i = Math.floor(Math.random()*m--);
    t = a[m];
    a[m] = a[i];
    a[i] = t;
  }
  return this;
}

const array = [0,1,2,3,4,5];
console.log(array[Symbol.for('shuffle')]());

JS-Symbolオブジェクト

A Pen by Takaaki Sato on CodePen.

License.