JavaScript returns 当我将参数设置为对象时出现 TypeError
JavaScript returns TypeError when I set the arguments as objects
我想在 JavaScript 中测试继承。我制作了一个示例脚本,但它不起作用。程序 returns 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 函数的参数设置为非对象,程序运行良好。
错误来自这一行:
Cat.prototype = new Mammal();
Mammal
构造函数需要一个具有 name
属性 的对象。你可以这样做:
Cat.prototype = new Mammal({name: null});
或者更好:
Cat.prototype = Object.create(Mammal.prototype);
我想在 JavaScript 中测试继承。我制作了一个示例脚本,但它不起作用。程序 returns 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 函数的参数设置为非对象,程序运行良好。
错误来自这一行:
Cat.prototype = new Mammal();
Mammal
构造函数需要一个具有 name
属性 的对象。你可以这样做:
Cat.prototype = new Mammal({name: null});
或者更好:
Cat.prototype = Object.create(Mammal.prototype);