(2018/10/15編集)この内容すごいJSビギナーの時に書いたやつでして
javascariptはclassやextends使えるので参考にしないほうがいいです。
とりあえずCompositeパターンで
なんとなくいい感じで記述できてるような気がせんでもないが
constructorとそれに付随する引数を取り入れたい…
クラスの書き方
var Component= function(){};
(function(){
var _this_ = Component.prototype;
////プロパティ////
_this_.parent;
_this_.name = "Component.prototype";
////メソッド////
//for Leaf and Conmpsite
_this_.operation = function(){
console.log(this.name + " : operation");
};
//for Composite
_this_.addChild = function(){};
_this_.removeChild = function(){};
_this_.getChild = function(){};
_this_.getParent = function(){
return this.parent;
};
_this_.setParent = function(parent){
this.parent = parent;
};
})();
継承の仕方
このモジュールを利用して継承させる。
調べたらNode.jsの中にこうやって継承しろと書かれていた。
inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
なのでこのinheritsモジュールを利用して
なんとなく継承している風に改行せずにすぐ後ろに書いてみる
var Composite= function(){}; inherits(Composite,Component);
(function(){
var _this_ = Composite.prototype;
////プロパティ////
_this_.child = new Array();
_this_.name = "Composite.prototype";
////メソッド////
_this_.addChild = function(component){
this.child.push(component);
this.child[this.child.length - 1].setParent(this);
};
_this_.removeChild = function(){
};
_this_.getChild = function(id){
return this.child[0];
};
})();
(function(){定義})を使ってるかというと
実際のプロパティやメソッドを記入するときに
「オブジェクト指向 クラス javascript」とかで調べたら
var Composite= function(){};
Composite.prototype={
////プロパティ////
child : new Array();,
name : "Composite.prototype",
////メソッド////
addChild : function(component){
this.child.push(component);
this.child[this.child.length - 1].setParent(this);
};,
removeChild = function(){
};,
getChild = function(id){
return this.child[0];
};
}
と記述されていてclassを作る分にはいいのですが
いざ継承する時にinherits(Composite,Component);
を利用して
var Composite= function(){}; inherits(Composite,Component);
Composite.prototype={
定義 中略
}
とするとせっかく継承したprototypeが全部上書きされちゃったので
これはダメだとたどりついたのが(function(){定義})を使用する事
だったのです。
以下、コンポジットパターン用にメモ
var Leaf= function(){}; inherits(Leaf,Component);
(function(){
var _this_ = Leaf.prototype;
_this_.name = "Leaf.prototype";
})();
(初心者です。アドバイス等あればお願いします。)