我正在 Codecademy 上学习 Javascript,我正在做一个任务,我必须记录两个人的物种(智人)和年龄。它返回一个 TypeError,这是一种我还没有见过的错误类型。错误是:
TypeError: Cannot read property 'species' of undefined
我的代码是:
function Person(name,age) {
this.name = name;
this.age = age;
this.species = "Homo Sapiens";
}
var sally = Person("Sally Bowles",39);
var holden = Person("Holden Caulfield",16);
console.log("sally's species is " + sally.species + " and she is " + sally.age);
console.log("holden's species is " + holden.species + " and he is " + holden.age);
非常感谢任何帮助或建议
最佳答案
您必须使用new
运算符创建对象类型的实例:
var sally = new Person('Sally Bowles', 39);
var holden = new Person('Holden Caulfield', 16);
console.log( sally.species, holden.species ); // "Homo Sapiens"
关于JavaScript 类型错误 : cannot read property 'species' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24507900/