- 履歴一覧
- 差分 を表示
- 現在との差分 を表示
- ソース を表示
- JavaScript/配列に独自の関数をもたせる へ行く。
- 1 (2018-05-14 (月) 10:26:53)
キーワード†
- JavaScript
- prototype
したいこと†
サーバーから受け取るリストはArrayとして扱える。そこに業務的な独自関数を追加して、ロジックの流出を防ぎたい。
どうやって†
コレクションをフィールドにもつなら†
ファーストクラスコレクションの形でデータをもつなら、その型のprototypeに関数をもたせることができる。
function FirstClassCollection() {
this.__content;
}
FirstClassCollection.prototype.size = function () {
return this.__content.length;
};
FirstClassCollection.prototype.map = function (...args) {
const newCollection = Object.create(Object.getPrototypeOf(this));
newCollection.__content = this.__content.map(...args);
return newCollection;
};
function asFirstClassCollection(target) {
Object.setPrototypeOf(target, FirstClassCollection.prototype);
return target;
}
function RaisableCollection() {
this.__content;
}
Object.setPrototypeOf(RaisableCollection.prototype, FirstClassCollection.prototype);
RaisableCollection.prototype.raise = function() {
return this.map(value => value * value)
};
function asRaisableCollection(target) {
Object.setPrototypeOf(target, RaisableCollection.prototype);
return target;
}
コレクションをフィールドにもたなくてもいい†
表示データとしてはわざわざコレクションをフィールドにもつファーストクラスコレクションの形にしないかもしれない。
JavaScriptではprototypeチェーンでArrayをラップして関数をもたせることができる。
function RaisableCollection() {
}
Object.setPrototypeOf(RaisableCollection.prototype, Array.prototype);
RaisableCollection.prototype.raise = function() {
return asRaisableCollection(
this.map(value => value * value)
);
};
function asRaisableCollection(target) {
Object.setPrototypeOf(target, RaisableCollection.prototype);
return target;
}
なお書き†
- 新しいclassもprototypeのシンタックスシュガーなんだってね。