4

私はいくつかのjavascript継承の例を試していますが、これで壁にぶつかりました:

function Animal(){}
Animal.prototype.type = "animal";
Animal.prototype.speak = function(){ console.log( "I'm a " + this.type + 
    ". I can't really talk ;)" ); }

function Dog(){}

function F(){}
F.prototype = Animal.prototype;

Dog.prototype = new F();
Dog.prototype.constructor = Dog;
Dog.prototype.type = "Dog";
Dog._super = Animal.prototype;
Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }

var rover = new Dog();
rover.woof();

私はこれを取得していますが、理由がわかりません:

TypeError: Object #<Dog> has no method 'woof'

見つからないメソッドをコンストラクター関数に入れることができることは知っていますが、プロトタイプを変更してこれを実行しようとしています。私はここで何が間違っているのですか?

4

5 に答える 5

4

Dog疑似クラス定義の最後の文字列が間違っています。そのはず

Dog.prototype.woof = function(){ console.log( "Woof!" ); Dog._super.speak.call(this); }
  1. メソッドは、のプロトタイプのwoofプロパティとして定義する必要があります。Dog
  2. _superDogコンストラクターのプロパティとしてのみ使用できます。
  3. 現在のインスタンスのコンテキストで親クラスのメソッドを呼び出す必要があります。
于 2011-10-12T04:43:32.093 に答える
4

変化する:

Dog._super = Animal.prototype;
Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }

に:

// Dog.prototype._super = Animal.prototype; <- you can remove this line
Dog.prototype.woof = function(){ console.log( "Woof!" ); this.speak(); }
于 2011-10-12T04:43:59.837 に答える
3

したがって、woofメソッドは実際には事実上静的メソッドです(Javaから来ている場合。基本的に、Dog関数からぶら下がっていて、Dogのインスタンスなしでアクセスできます。つまり:Dog.woof())

犬のインスタンスで動作させるには、それがプロトタイプ定義であることを確認する必要があります(ここでも、Javaの例えで、事実上インスタンスメソッド定義です)。qwertymikが言ったように、

Dog.prototype.woof = function(){ console.log( "Woof!" ); this.speak(); }

その後、あなたはすることができるようになります

var foo = new Dog();
foo.woof();
于 2011-10-12T04:48:07.710 に答える
1

多分あなたはこれをするつもりです:

Dog.prototype._super = Animal.prototype;
Dog.prototype.woof = function(){ console.log( "Woof!" ); this._super.speak(); }
于 2011-10-12T04:44:26.870 に答える
0
//Rewrote the code to make it work

function Animal(){}
Animal.prototype.type = "animal";
Animal.prototype.speak = function(){ console.log( "I'm a " + this.type + 
    ". I can't really talk ;)" ); }

function Dog(){}
function F(){}

F.prototype = Object.create(Animal.prototype); //F inherits from animal
Dog.prototype = Object.create(F.prototype);    //Dog inherits from F

Dog.prototype.constructor = Dog; //resetting the constructor to Dog object
F.prototype.constructor=F;       // resetting the constrctor to F object 

Dog.prototype.type = "Dog";

Dog.prototype.woof = function(){ console.log( "Woof!" ); this.speak(); } //adding woof method to the prototype of dog

const rover = new Dog();

rover.woof();

// output
// Woof!
// I'm a Dog. I can't really talk ;)
于 2019-03-05T23:23:50.490 に答える