関数 apply を使用して、クラス B をクラス A に、クラス A をクラス Super に拡張しようとしています。次のコードは問題なく動作します。
function Super() {
this.talk = function () {
alert("Hello");
};
}
function A() {
// instance of A inherits Super
Super.apply(this);
}
function B() {
// instance of B inherits A
A.apply(this);
}
var x = new B();
x.talk(); // Hello
しかし、インスタンスだけでなくクラス Super からクラス A を継承したい場合はどうすればよいでしょうか。私はこれを試しました:
function Super() {
this.talk = function () {
alert("Hello, I'm the class");
};
// function of the class' instance?
this.prototype.talk = function () {
alert("Hello, I'm the object");
};
}
function A() {
// nothing here
}
// A inherits from Super, not its instance
Super.apply(A);
function B() {
// instance of B inherits A
A.apply(this);
}
A.talk(); // static function works!
var x = new B();
x.talk(); // but this doesn't...
私は何か間違ったことをしていますか?