JavaScriptオブジェクト思考*1#01

prototypeを用いたクラスの作成と継承

クラス作成
Super = function(){};
Super.prototype =
{
    prop1 : "prop1",
    prop2 : "prop2"
};
クラスの継承
Basic = function(){};
Basic.prototype = new Super;
Basic.prototype.method1 = function(){};
Basic.prototype.method2 = function(){};
でもインスタンス化が必要
basic = new Basic;
basic.method1();

少し工夫

関数の実装
Factory = function(o)
{
    var f = function(){};
    f.prototype = o;
    return new f;
};
オブジェクトを作成し継承する
Super = {};
Super.prop1 = "prop1";
Super.prop2 = "prop2";

Basic = Factory(Super);
Basic.method1 = function(){};
Basic.method2 = function(){};

alert(Basic.prop1); // prop1
alert(Basic.prop2); // prop2
実装次第

結局prototypeはオブジェクトであるのでオブジェクトを代入する限りprototypeチェーンは繋がりますよと。別名前空間のオブジェクトをインポートできるので便利かもなと。

こんなことも

Singleton = function()
{
    var f = function(){};
    f.prototype = Super; // Super限定です。
    return function(){
        return new f;
    }
}();

super1 = new Singleton;
super2 = new Singleton;