当我将参数设置为对象时,JavaScript返回TypeError

时间:2015-03-23 07:56:41

标签: javascript oop inheritance prototype typeerror

我想在JavaScript中测试继承。我制作了一个示例脚本,但它不起作用。该程序返回TypeError。

var Mammal = function(spec) {
    this.name = spec.name;
};

Mammal.prototype.get_name = function() {
    return this.name;
};

var Cat = function(spec) {
    this.name = spec.name;
};  

Cat.prototype = new Mammal();

var cat = new Cat({name: 'Mike'});
console.log(cat.get_name());

如果我将Mammal和Animal函数的参数设置为非对象,则程序运行良好。

1 个答案:

答案 0 :(得分:3)

错误来自这一行:

Cat.prototype = new Mammal();

Mammal构造函数需要一个具有name属性的对象。你可以这样做:

Cat.prototype = new Mammal({name: null});

或者更好:

Cat.prototype = Object.create(Mammal.prototype);