在练习JavaScript时,我没想到Course.prototype.conflictsWith中间会发生上下文更改。第一个“ this”是指课程实例,而第二个“ this”是指全局对象。除了解决问题外,我还想了解为什么会这样。谢谢!
function Course(name, department, numCredits, timeBlock, daysOfTheWeek) {
this.name = name;
this.department = department;
this.numCredits = numCredits;
this.timeBlock = timeBlock;
this.daysOfTheWeek = daysOfTheWeek;
this.students = [];
}
Course.prototype.conflictsWith = function(course) {
this.daysOfTheWeek.forEach(function(day) {
if (course.daysOfTheWeek.includes(day)) {
if (this.timeBlock === course.timeBlock) return true;
}
});
return false;
}