ECMAScript5時代のクラス定義
Firefox4でES5のプロパティ定義がサポートされるようなので,実際に使うときに備えて覚え書きしてみる。
これまでこんな感じで書いてたJavaScriptのクラス定義。
// クラス const Hoge = function(prop) { this._prop = prop; }; Hoge.prototype = { _prop: null, get prop() this._prop, set prop(value) this._prop = value, method: function() {} }; let hoge = new Hoge(); // シングルトン const Fuga = { _prop: null, get prop() this._prop, set prop(value) this._prop = value, method: function() {} };
今後はこう書くと良いかも?
// クラス const Hoge = function(prop) { this._prop = prop; }; Object.defineProperties(Hoge.prototype, { _prop: { value: null, enumerable: false }, prop: { get: function() this._prop, set: function(value) this._prop = value }, method: { value: function() {}, writable: false, configurable: false } }); Hoge.preventExtensions(); let hoge = new Hoge(); hoge.preventExtensions(); // シングルトン const Fuga = Object.create({}, { _prop: { value: null, enumerable: false }, prop: { get: function() this._prop, set: function(value) this._prop = value }, method: { value: function() {}, writable: false, configurable: false } }); Fuga.preventExtensions();
定数プロパティとか,プロパティの追加ができないオブジェクトが作れるようになるのはすごくうれしいけど,実際に書いてみると結構めんどくさい。けどプロパティ名の記述ミスを減らすのにはすごく貢献してくれそうだから頑張って書いていこうと思う。