[英]Not sure why I'm getting this TypeError
I'm using classes and objects to create a list of stuff in javascript (I'm pretty new to programming).我正在使用类和对象在 javascript 中创建内容列表(我对编程很陌生)。 Now, I thought I had this right but for some reason it's throwing a
现在,我认为我有这个权利,但出于某种原因,它抛出了一个
"Uncaught TypeError: courseList.calculateValue is not a function at assignment.js:27"
“未捕获的类型错误:courseList.calculateValue 不是 assignment.js:27 处的函数”
Can't figure out why this isn't working.无法弄清楚为什么这不起作用。 Please help!
请帮忙! Here's my code:
这是我的代码:
You have an object courseList with nested array courses, that actually contains objects of class Course.您有一个带有嵌套数组课程的对象 courseList,它实际上包含 Course 类的对象。
courseList doesnt have this methods, because they were defined inside Course class. courseList 没有这个方法,因为它们是在 Course 类中定义的。 To execute this methods you need to do courseList.courses[0].calculateValue() and courseList.courses[1].calculateValue()
要执行此方法,您需要执行 courseList.courses[0].calculateValue() 和 courseList.courses[1].calculateValue()
Looks like you're calling calculateValue()
on an object that is not a Course
object.看起来您是在一个不是
Course
对象的对象上调用calculateValue()
。
In your case you need to do courseList.courses[0].calculateValue()
to calculate the value of the first course.在您的情况下,您需要执行
courseList.courses[0].calculateValue()
来计算第一门课程的价值。 And likewise you can do it for other courses by changing the index.同样,您可以通过更改索引来为其他课程执行此操作。
Longer explanation更长的解释
courseList
(badly named) is an object with just one property called courses
. courseList
(严重命名)是一个属性称为对象courses
。
This property has a value which is a list of Course
objects.这个属性有一个值,它是一个
Course
对象列表。 So in order to call methods from the Course
class on these objects you need to access them by first accessing the value of the course
property in courseList
and then choosing one of the courses from the list using an index like courseList.courses[1]
因此,为了在这些对象上调用
Course
类中的方法,您需要首先访问courseList
course
属性的值,然后使用诸如courseList.courses[1]
类的索引从列表中选择一门课程来访问它们
courseList.courses[1]
is now a Course
object so you can call calculateValue()
and printSummary()
on it courseList.courses[1]
现在是一个Course
对象,因此您可以在其上调用calculateValue()
和printSummary()
Side Note边注
Your console.log()
statement on line 28 won't print your results (even when you make the fix above) since printSummary
doesn't return anything.您在第 28 行的
console.log()
语句不会打印您的结果(即使您进行了上述修复),因为printSummary
不返回任何内容。 You don't need to call console.log()
on it at all, since printSummary
handles the printing within it您根本不需要调用
console.log()
,因为printSummary
处理其中的打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.