原型继承为什么子对象不从父对象继承方法

Prototypal Inheritance Why Does Child Object Not Inherit Method From Parent Object?

本文关键字:继承 对象 方法 原型 为什么      更新时间:2023-09-26

这是我的JavaScript:

http://jsfiddle.net/GPNdM/

我有一个Cat对象,它扩展了Mammal的原型。Mammal有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();

知道为什么吗?

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

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