如何让最后一行工作?
function Animal(name){
this.name = name;
}
Animal.prototype.speak = function(){
alert('Hi, I\'m ' + this.name);
}
function Dog(name){
this.name = name;
}
Dog.prototype.bark = function(){
alert('Woof!');
};
var fido = new Dog('Fido');
fido.bark(); // Woof!
fido.speak(); // Hi, I'm Fido *can't get this to work*
答案 0 :(得分:7)
Dog.prototype = new Animal();
答案 1 :(得分:1)
...
function Dog(name){
this.name = name;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor= Dog;
Dog.prototype.bark = function(){
alert('Woof!');
};
...
Object.create创建一个新的空对象,并使用该对象的原型参数。
您也可以在构造函数中创建继承:
function Dog(name){
Animal.call(this, name);
this.name = name;
}
在这里,您可以在新的Dog上下文中调用Animal构造函数。
答案 2 :(得分:1)
总之;你可以这样做:
var Dog = function(name){
//re use Animal constructor
Animal.call(this,name);
//you can do Animal.apply(this,arguments); as well
};
//set up the prototype chain
Dog.prototype = Object.create(Animal.prototype);
//repair the constructor property
Dog.prototype.constructor = Dog;
可以找到构造函数,继承和原型的介绍here。