LoginSignup
2
2

More than 5 years have passed since last update.

ES6でprotectedメンバを簡潔に定義する

Last updated at Posted at 2016-02-18

自分がよく使っている方法メモ。
WeakMapを使った privateメンバ protectedメンバの実装の見た目を少しスッキリさせただけ。
(最初privateメンバ実装したつもりでしたが、コメントでご指摘いただいた通りprotectedだったので修正しました)

まず、以下のような関数をどこかに適当なファイル内で定義する。
この関数は、外部からアクセスできないWeakMapに値を出し入れすることで、
privateな変数を実現している。

const privates = new WeakMap();
module.exports = (self) => {
  if (!privates.has(self)) {
    privates.set(self, {});
  }

  return privates.get(self);
}

次に、privateなメソッドを定義したいクラスで上記関数を読み込んで使う。

const _ = require('./private.js');

class Person {
  constructor(name) {
    _(this).name = name;
  }

  print() {
    console.log(_(this).name);
  }
}

いえい

const person = new Person('test');
person.print(); // "test"

実はprotectedですらない

外部から_(person).nameとかやればアクセスできてしまうので厳密にはprotectedでは無いが、
明示的にアクセスしない限りはアクセス出来ないので、余程の事がない限り問題無いはず。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2