如何正确地使构造函数起作用?

时间:2018-06-28 18:59:28

标签: javascript constructor

任何对此的帮助将不胜感激。即使我觉得我尝试的代码是正确的,我似乎也无法弄清楚。 sayNametakeAttendance不是函数给我一个错误。预先感谢!

这是我正在尝试的:

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 :(得分:1)

您实际上不是在创建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());