gpt4 book ai didi

JavaScript 类型错误 : cannot read property 'species' of undefined

转载 作者:行者123 更新时间:2023-11-28 19:44:41 25 4
gpt4 key购买 nike

我正在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com