Как правильно заставить конструктор работать? - PullRequest
0 голосов
/ 28 июня 2018

Любая помощь с этим будет принята с благодарностью. Я просто не могу понять это, хотя чувствую, что код, который я пробую, верен. Это дает мне ошибку, что sayName и takeAttendance не являются функциями. Заранее спасибо!

Вот что я пытаюсь:

function Cohort(program, campus, number, students=['Bill', 'Ted', 'Bob']) {
  this.program = program;
  this.campus = campus;
  this.number = number;
  this.students = students;
  this.sayName = function() {
    return 'This cohort is called ' + this.program + this.campus + this.number;
  }
  this.takeAttendance = function() {
    console.log(this.students);
  }
}

cohort1 = {
  program: 'w',
  campus: 'pr',
  number: 27,
  students: ['Preston', 'Katie', 'Chester']
}

cohort2 = {
  program: 'w',
  campus: 'pr',
  number: 31,
  students: ['Brendan Eich', 'Dan Abramov', 'Wes Bos', 'Kent Dodds', 'Billy Bob']
}

cohort1.sayName();
cohort2.takeAttendance();

1 Ответ

0 голосов
/ 28 июня 2018

Вы на самом деле не создаете Cohort с. Подумайте, как вы делаете cohort1:

cohort1 = {
  program: 'w',
  campus: 'pr',
  number: 27,
  students: ['Preston', 'Katie', 'Chester']
}

Здесь нет ничего, что указывало бы движку JavaScript на создание Cohort. Вместо этого вы назначаете литерал Object переменной cohort1.

Вместо этого вам нужно вызвать созданную вами функцию Cohort:

var cohort1 = new Cohort("w", "pr", 27, ['Preston', 'Katie', 'Chester']);

Вы можете увидеть, как это работает правильно в исполняемом фрагменте ниже.

function Cohort(program, campus, number, students = ['Bill', 'Ted', 'Bob']) {
  this.program = program;
  this.campus = campus;
  this.number = number;
  this.students = students;
  this.sayName = function() {
    return 'This cohort is called ' + this.program + this.campus + this.number;
  }
  this.takeAttendance = function() {
    console.log(this.students);
  }
}

// Use new Cohort(...) to actually create a Cohort and assign it to cohort1
var cohort1 = new Cohort("w", "pr", 27, ['Preston', 'Katie', 'Chester']);

console.log(cohort1.sayName());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...