1

継承を実装する関数があります:

inherit = function(base) {
    var child = function() { console.log('Crappy constructor.'); };
    child.prototype = new base;
    child.prototype.constructor = child;
    return child;
}

次のように使用できると思いました。

var NewClass = inherit(BaseClass);
NewClass.prototype.constructor = function() {
    console.log('Awesome constructor.');
}

しかし、次のようにNewClassの新しいインスタンスを作成すると:

var instance = new NewClass();

Crappy constructorというメッセージが表示されます。コンソールに出力されています。コンストラクターが上書きされないのはなぜですか? また、どうすれば上書きできますか?

4

1 に答える 1

2

childprint する関数である を返しますCrappy constructor。その関数を呼び出すと、何があってCrappy constructorも印刷されます。

フローに注意してください:

child = function to print 'crappy'
child.prototype.blabla = function to print 'Awesome'
inherit returns child

NewClass = child

これで、NewClass を呼び出すと、child が呼び出されます。

それ以外では、prototype.constructor ではなく child.constructor.prototype が必要だったと思います。

編集: Javascript での継承の詳細については、こちらを参照してください。

于 2012-05-10T06:18:37.760 に答える