1

親クラスから拡張し、1つのメソッドをオーバーロードして、それをわずかに変更するjavascriptクラスを作成しようとしています。

たとえば、いくつかの変数をチェックします。それらがtrueに設定されている場合は、親に対して同じメソッドを実行します。それ以外の場合は、いくつかの異なるコードを実行します。

これは私が思いついたものです:

function Dad(name)    
{
    this.yell = function()
    {
        console.log( 'GRRRRRRR ' + name);
    }
}

function Kid(name, age)    
{
    var parent = new Dad(name);


    parent.yell = function()
    {
        if (age < 15)
            console.log( 'BAAAAA ' + name );
        else
            parent.yell(); //This is the problem line, how to call this method on
                           //parent object
    }
    return parent;
}

var k = new Kid('bob', 13);
k.yell();

ただし、問題は、親オブジェクトのメソッドを呼び出す方法です。

何か案は?

4

1 に答える 1

2

プロトタイプを使用します。スーパークラスのメソッドにアクセスできますが、インスタンス化する必要はありません。

次に、子クラスから、SuperClass.prototype.instanceMethod.call(this)基本的superにほとんどの典型的な OO 言語で行うことができますが、JS はスーパークラスが何であるかを理解するのに役立ちません。そのため、自分で追跡する必要があります。

// Superclass
function Dad() {};
Dad.prototype.yell = function() {
    console.log("Do your homework!");
}

// Subclass
function Kid(age) {
    // calls the constructor of the superclass.
    // in this case, the Dad() constructor does nothing, so it's not required here.
    Dad.call(this);

    // save constructor argument into this instance.
    this.age = age;
};

// Inheritance happens here, prototype is an instance of superclass
Kid.prototype = new Dad();

// Make sure the constructor is properly assigned.
Kid.prototype.constructor = Kid;

// Override an instance method.
Kid.prototype.yell = function() {
    if (this.age < 18) {
        console.log('Waaaaa, I hate homework');
    } else {
        // calls the yell method of the superclass
        Dad.prototype.yell.call(this);
    }
}

// make a kid.
var k = new Kid(13);
k.yell(); // 'Waaaaa, I hate homework' 

// make an old kid.
var k = new Kid(30);
k.yell(); // 'Do your homework!' 

JS でのオブジェクト指向の継承は厄介な場合がありますが、役立つものがいくつかあります。

いくつか挙げると。

于 2012-12-19T21:03:15.983 に答える