JavaScript で親クラスのコンストラクタを呼ばずに継承を行う
JavaScript の prototype を使った継承のオーソドックスな形は以下のような感じだと思います。
function SuperClass(name) { this.name = name; } SuperClass.prototype.hello = function() { alert(this.name+" : hello!"); } function ChildClass() { SuperClass.call(this, "Koyomi Araragi"); } ChildClass.prototype = new SuperClass(""); new ChildClass().hello();
親クラスのprototypeにアクセスするために、ChildClass.prototype に親クラスのインスタンスを生成して代入しています。これにより ChildClass のインスタンスから親クラスの hello が呼べるようになります。
この方法だと、継承のたびに親クラスのコンストラクタを呼ばなければなりません。親クラスのコンストラクタが、無効な引数に対して例外を投げる設計だったり、問題となる副作用を持っていたりすると厄介です。
以下のようにすると、親クラスのコンストラクタを呼ばずに継承を行えます。
function createObjectForPrototype(type) { var f = function(){}; f.prototype = type.prototype; return new f(); } function SuperClass(name) { this.name = name; } SuperClass.prototype.hello = function() { alert(this.name+" : hello!"); } function ChildClass() { SuperClass.call(this, "Koyomi Araragi"); } ChildClass.prototype = createObjectForPrototype(SuperClass); new ChildClass().hello();