我想在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函数的参数设置为非对象,则程序运行良好。
答案 0 :(得分:3)
错误来自这一行:
Cat.prototype = new Mammal();
Mammal
构造函数需要一个具有name
属性的对象。你可以这样做:
Cat.prototype = new Mammal({name: null});
或者更好:
Cat.prototype = Object.create(Mammal.prototype);