JavaScript:在函数中更改上下文

时间:2019-07-13 19:45:06

标签: javascript javascript-objects

在练习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;
}

0 个答案:

没有答案