Javascript原型继承古怪

问题描述 投票:4回答:5

我正在尝试通过一些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'

我知道我可以将未找到的方法放入构造函数中,但我正在尝试使用原型修改。我在这做错了什么?

javascript inheritance prototypal-inheritance
5个回答
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(); }

4
投票

Dog伪类定义的最后一个字符串是错误的。它应该是

Dog.prototype.woof = function(){ console.log( "Woof!" ); Dog._super.speak.call(this); }
  1. 您应该将方法woof定义为Dog原型的属性。
  2. _super仅作为Dog构造函数的财产。
  3. 您应该在当前实例的上下文中调用父类的方法。

3
投票

所以你的woof方法实际上是一个静态的方法(如果你来自java。基本上,它是挂起Dog函数,可以在没有Dog实例的情况下访问。即:Dog.woof())

为了让它与一个狗的实例一起工作,你想确保它是一个原型定义(再次,使用Java类比,实际上是一个实例方法定义)。正如qwertymik所说,

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

那你就能做到

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

1
投票

也许你的意思是这样做:

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

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 ;)
© www.soinside.com 2019 - 2024. All rights reserved.