LoginSignup
28
29

More than 5 years have passed since last update.

JavaScriptでの静的クラスと動的クラスの作り方

Last updated at Posted at 2014-08-22
//----------------------------------------------
// static class
//----------------------------------------------
window.A = {

    _bar: 'メンバ変数',

    hoge: function(){
        return this._foo( this._bar );
    },

    _foo: function( arg ){
        alert( arg );
    }
};

//呼び出し方
A.hoge();

//----------------------------------------------
// dynamic class (instance, object)
//----------------------------------------------
window.A = function(){

    var bar = 'メンバ変数';

    alert('コンストラクタ');

    this.hoge = function(){
        return foo( bar );
    }

    function foo( arg ){
        alert( arg );
    }
}

//呼び出し方
var a = new A();
a.hoge();

解説

個別のメンバ変数をもたせたい場合は動的クラスで書いてnewすればいいですよね。
そうでなくて、メソッドもメンバ変数もすべて共通なら静的クラスを扱います。

今回はJavaScriptでの静的クラス、動的クラスの書き方を紹介しました。

隠蔽化
この静的クラスのとき、メソッドもメンバ変数も外からアクセスできちゃうので、明示的にアンダースコアさん(_)をプレフィックスしてあげましょう。

静的クラスのコンストラクタ
必要なかろーもん!

継承
継承はできないのでprototypeをつかってください(逃

28
29
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
28
29