LoginSignup
6
6

More than 5 years have passed since last update.

クラス継承

Last updated at Posted at 2012-02-16

///////////////////////////////////////////////////////////////////////
//
// clazz
//
///////////////////////////////////////////////////////////////////////


var clazz = function (Parent, props) {

    var Child;
    var F;
    var i;

    //------------------------------------------
    //coustruct
    //------------------------------------------


    Child = function () {
        if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
            Child.uber.__construct.apply(this, arguments);
        }
        if (Child.prototype.hasOwnProperty("__construct")) {
            Child.prototype.__construct.apply(this, arguments);
        }
    };


    //------------------------------------------
    //extends
    //------------------------------------------

    Parent = Parent || Object;
    F = function () {
    };
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.uber = Parent.prototype;
    Child.prototype.constructor = Child;


    //------------------------------------------
    //add methods
    //------------------------------------------

    for(i in props){

        if(props.hasOwnProperty(i)) {
            Child.prototype[i] = props[i];
        }
    }


    //------------------------------------------
    // return
    //------------------------------------------

    return Child;

};


//===========================================================
// clazz SAMPLE
//===========================================================


/**
 * Man
 */
var Man = clazz(null,
    {
        __construct:function (what) {
            alert("Man.__construct");
            this.name = what ;
        }

        ,getName:function () {
            return this.name;
        }
    }
);

/**
 * SuperMan
 */
var SuperMan = clazz(Man,
    {
        __construct:function(what){
            alert("SuperMan  __construct")
        }

        ,getName:function(){
            var name = SuperMan.uber.getName.call(this);
            return "I am " + name;
        }
    }
);


//
// 実行テスト
//
var superMan = new SuperMan("itoz");
alert(superMan.getName());//itoz

6
6
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
6
6