私はそれをよりよく理解するためにjsでいくつかの継承を行ってきましたが、私を混乱させる何かを見つけました.
new キーワードを使用して「コンストラクター関数」を呼び出すと、その関数のプロトタイプへの参照を含む新しいオブジェクトが取得されることを私は知っています。
また、プロトタイプの継承を行うには、コンストラクター関数のプロトタイプを、「スーパークラス」にしたいオブジェクトのインスタンスに置き換える必要があることも知っています。
だから私はこれらの概念を試すためにこのばかげた例を作りました:
function Animal(){}
function Dog(){}
Animal.prototype.run = function(){alert("running...")};
Dog.prototype = new Animal();
Dog.prototype.bark = function(){alert("arf!")};
var fido = new Dog();
fido.bark() //ok
fido.run() //ok
console.log(Dog.prototype) // its an 'Object'
console.log(fido.prototype) // UNDEFINED
console.log(fido.constructor.prototype == Dog.prototype) //this is true
function KillerDog(){};
KillerDog.prototype.deathBite = function(){alert("AAARFFF! *bite*")}
fido.prototype = new KillerDog();
console.log(fido.prototype) // no longer UNDEFINED
fido.deathBite(); // but this doesn't work!
(これは Firebug のコンソールで行われました)
1) すべての新しいオブジェクトにクリエーター関数のプロトタイプへの参照が含まれている場合、fido.prototype が定義されていないのはなぜですか?
2) 継承チェーンは [obj] -> [constructor] -> [prototype] ではなく [obj] -> [prototype] ですか?
3) オブジェクト (fido) の「プロトタイプ」プロパティはチェックされていますか? もしそうなら...なぜ「deathBite」は(最後の部分で)未定義なのですか?