3

関数 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...

私は何か間違ったことをしていますか?

4

2 に答える 2

4
function Super() { }

// Static method, called by Super.talk()
Super.talk = function () {
    alert("Hello, I'm the class");
};

// Prototype method, should be called by instance
Super.prototype.talk = function () {
    alert("Hello, I'm the object");
};

function A() {
    // 'override' purposes
    Super.apply(this, arguments);
    // ..
}

// A inherits from Super
A.prototype = Object.create(Super.prototype);
A.prototype.constructor = A;

function B() { 
    A.apply(this, arguments);
}

// B inherits from A
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

// A.talk() won't work, of course.

var x = new B();
x.talk();
于 2013-09-23T14:06:16.327 に答える
1

パブリック プロパティとメソッドをクラス (関数クラスではなく) に追加するには、次の 2 つの方法があります。

パブリック プロパティを追加する方法 1、各インスタンスに追加:

function MyClass(){
      this.publicProperty = 'public property'; 
}

パブリック プロパティを追加する方法 2、プロトタイプに追加、すべてのインスタンスに共通:

MyClass.prototype.publicMethod = function(){
      console.log('public method');
}

から継承するClass場合は、すべてのパブリック プロパティとメソッドを継承する必要があります。

方法 1 を使用して追加されたプロパティとメソッドを継承する:

function MyDerivedClass(){
      MyClass.apply(this);
}

方法 2 を使用して追加されたプロパティとメソッドを継承する:

MyDerivedClass.prototype = Object.create(MyClass.prototype);

したがって、あなたの場合、あなたは実際にofにメソッドをSuper.apply(A);追加しています(1経由でメソッド2を使用しています)。ただし、メソッド 1 を使用してプロパティのみから継承します。関数を宣言した後に以下の行を追加するだけです。talkprototypeABAB

B.prototype = Object.create(A.prototype);

そして、物事はあなたが期待するように機能します。これが役に立てば幸いです。

于 2013-09-23T18:54:43.113 に答える