0

javascriptで継承しようとしています。まず、ネットで調べていたらこれを見つけました

function A() {}
function B(){}
B.prototype = new A() ;
B.prototype.constructor = B ;

これは機能しますが、 B のプロトタイプ プロパティを使用すると機能しなくなります ( http://jsfiddle.net/jeanluca/eQBUx/ )

function A() {}
A.prototype.bar = function(){ return 'A'; }

function B() {}
B.prototype.bar = function(){ return 'B'; }

私はあなたができることを理解しています

function B(){ this.bar = function(){ ... } } ;

しかし、これはプロトタイプを使用して定義するよりも確実に遅いと思います。では、2 番目の状況で継承を行うにはどうすればよいでしょうか。

thnx

4

3 に答える 3

2

後で完全に置き換えるプロトタイプオブジェクトにプロパティを作成しています。逆に、新しいオブジェクトにbarメソッドを作成します。そして使用しないでくださいnew

function B() {}
// first create the prototype object
B.prototype = Object.create(A.prototype);
// then assign properties on it
B.prototype.bar = function(){ return 'B'; }
于 2013-08-05T11:43:29.723 に答える
2

コードは次のとおりです。

function A() {}
A.prototype.bar = function(){ return 'A';}

function B() {}
B.prototype.bar = function(){ return 'B'; }
B.prototype = new A() ; // replaces B's "bar" with A's "bar

var b = new B ;
console.log(b.bar());

ご覧のとおり、問題は 6 行目にあります。最初B.prototype.barに 5 行目で関数を設定し、次にすぐに6 行目に設定B.prototypeしますnew A(5 行目で行ったことを効果的に元に戻します)。解決策は、6 行目を 5 行目の前に置くことです。

function A() {}
A.prototype.bar = function(){ return 'A';}

function B() {}
B.prototype = new A() ; // now it will work
B.prototype.bar = function(){ return 'B'; }

var b = new B ;
console.log(b.bar());

デモをご覧ください: http://jsfiddle.net/eQBUx/1/

さらに、Bergi:キーワードの使用newをやめることに同意します。


更新:あなたのコメントを読み、あなたの問題をより詳細に理解した後、私のaugmentライブラリを継承に使用することをお勧めします:

var A = Object.augment(function () {
    this.constructor = function () {};

    this.bar = function () {
        return "A";
    };
});

var B = A.augment(function (base) {
    this.constructor = function () {};

    this.bar = function () {
        return "B" + base.bar.call(this);
    };
});

var b = new B;

console.log(b.bar());

デモを参照してください: http://jsfiddle.net/eQBUx/2/

于 2013-08-05T11:58:32.850 に答える
2

を使用thisしてプロパティを割り当てると、プロトタイプ チェーンが壊れます。これは非常に非効率的であり、継承を取得するために使用することはできません。だから..しない?

于 2013-08-05T11:40:09.103 に答える