我正在尝试通过一些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'
我知道我可以将未找到的方法放入构造函数中,但我正在尝试使用原型修改。我在这做错了什么?
更改:
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(); }
Dog伪类定义的最后一个字符串是错误的。它应该是
Dog.prototype.woof = function(){ console.log( "Woof!" ); Dog._super.speak.call(this); }
woof
定义为Dog
原型的属性。_super
仅作为Dog
构造函数的财产。所以你的woof方法实际上是一个静态的方法(如果你来自java。基本上,它是挂起Dog函数,可以在没有Dog实例的情况下访问。即:Dog.woof())
为了让它与一个狗的实例一起工作,你想确保它是一个原型定义(再次,使用Java类比,实际上是一个实例方法定义)。正如qwertymik所说,
Dog.prototype.woof = function(){ console.log( "Woof!" ); this.speak(); }
那你就能做到
var foo = new Dog();
foo.woof();
也许你的意思是这样做:
Dog.prototype._super = Animal.prototype;
Dog.prototype.woof = function(){ console.log( "Woof!" ); this._super.speak(); }
//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 ;)