12
11

More than 5 years have passed since last update.

クラスの書き方と継承

Last updated at Posted at 2014-08-24

(2018/10/15編集)この内容すごいJSビギナーの時に書いたやつでして
javascariptはclassやextends使えるので参考にしないほうがいいです。

とりあえずCompositeパターンで
なんとなくいい感じで記述できてるような気がせんでもないが
constructorとそれに付随する引数を取り入れたい…

クラスの書き方

Component.js
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.js
inherits = function(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
};

なのでこのinheritsモジュールを利用して
なんとなく継承している風に改行せずにすぐ後ろに書いてみる

Composite.js
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」とかで調べたら

違うclassの書き方
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(){定義})を使用する事
だったのです。

以下、コンポジットパターン用にメモ

Leaf.js
var Leaf= function(){}; inherits(Leaf,Component);
(function(){
var _this_ = Leaf.prototype;
    _this_.name = "Leaf.prototype";
})();

(初心者です。アドバイス等あればお願いします。)

12
11
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
12
11