コードは次のとおりです。
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/