2013-06-28 200 views
0

因此,这里是我的JavaScript:原型继承为什么子对象不能从父对象继承方法?

http://jsfiddle.net/GPNdM/

我有延伸哺乳动物的原型猫对象。哺乳动物有run()方法。但是当我创建新的Cat对象并调用run()时,它告诉我它是未定义的:

function Mammal(config) { 
    this.config = config; 
} 
Mammal.prototype.run = function() { 
    console.log(this.config["name"] + "is running!"); 
} 

function Cat(config) { 
    // call parent constructor 
    Mammal.call(this, config); 
} 
Cat.prototype = Object.create(Mammal); 

var felix = new Cat({ 
    "name": "Felix" 
}); 
felix.run(); 

任何想法为什么?

+0

您的对象一般不会继承函数对象。大多数情况下,它们将通过'.prototype'属性从函数中悬挂的奇怪小对象继承。 –

回答

5

它应该是Cat.prototype = Object.create(Mammal.prototype),这就是方法所在,而不是直接在Mammal上。

http://jsfiddle.net/GPNdM/1/

+1

谢谢。仍然试图围绕这个原型继承:P –