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. 您应该将方法定义woofDog原型的属性。
  2. _super仅作为Dog构造函数的属性可用。
  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 回答