prototype継承するときの順序には気をつける
prototype継承を実装する時の凡ミスが多いです。
function GrandParent() { } function Parent() { } function Me() { } // GrandParentにhelloメソッドを追加 GrandParent.prototype.hello = function() { }; // Parentにworldメソッドを追加 Parent.prototype.world = function() { }; // GrandParentをPrototype継承 Parent.prototype = new GrandParent(); // ParentをPrototype継承 Me.prototype = new Parent(); var me = new Me; me.world(); // Error
上記の例のように、prototypeに対してfunctionを定義した後に、prototype継承を行うと、prototypeというプロパティの値がごっそり書き換えられてしまうので、worldもなくなってしまいます。
function GrandParent() { } function Parent() { } function Me() { } GrandParent.prototype.hello = function() { }; // 先にPrototype継承を行う Parent.prototype = new GrandParent(); Parent.prototype.world = function() { }; Me.prototype = new Parent(); var me = new Me; me.world(); // OK
Prototype継承する時は、Prototypeを拡張する前に実行しなければならないので、気をつけます。