在Javascript中使用工厂创建对象

时间:2016-05-27 10:31:00

标签: javascript

我正在尝试使用factory创建两个 person 类型的对象,并在第一次尝试时创建第一个元素,第二次尝试而不是创建第二个元素创建一个新元素,但与第一个元素具有相同的特征

班级Person

function Person(id, name) {
  this.id = id;
  this.name = name;
}

班级Student extends Person

function Student(id, name) {
  Person.call(this, id, name);
}

班级Teacher extends Person

function Teacher(id, name) {
  Person.call(this, id, name);
}

使用函数factory创建学生和教师

function Factory() {
  this.createPerson = function(type, name) {
    var person;
    var idStudent = 0;
    var idTeacher = 0;

    switch (type) {
      case "1":
        person = new Student(idStudent++, name);
        break;
      case "2":
        person = new Teacher(idTeacher++, name);
        break;
    }
    return person;
  }
}

班级School有一个人数组

function School(id) {
  this.persons = [];
  this.factory = new Factory();
  this.personCreate = null;

  this.createStudentAndTeacher = function() {
    var type = prompt("Choose ? \n\n[1-Student | 2-Teacher ]");
    var name = prompt("Write name?");

    if (type !== null) {
      this.personCreate = this.factory.createPerson(type,name);
      this.persons.push(this.personCreate);
    } else {
      alert("need to choose");
    }
  }
}

默认创建

var s = new School(1);

var btn = document.createElement('button');
btn.value = "create";
btn.onclick = function(){
  s.createStudentAndTeacher();
}

我怀疑的是,当我创建名为“John”Student对象时,返回 student.id = 0 student.name = John 但是当我创建名为“Elisa”的新Student对象时,请返回相同的信息 student.id = 0 student.name = John ,事实上,应该返回 student.id = 1 student.name = Elisa ,如果我创建新的Teacher名称为“Jerry”的对象,返回相同的信息 student.id = 0 student.name = John ,实际上应返回< strong> teacher.id = 0 和 teacher.name = Jerry

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您的createPerson正在重新声明idStudentidTeacher(并将其重置为0)。尝试将该代码移出该块。

答案 1 :(得分:2)

代码有错误。在Factory定义中,更改此

function Factory() {
  this.createPerson = function(type, name) {
    var person;
    var idStudent = 0;
    var idTeacher = 0;

到这个

function Factory() {
  var idStudent = 0;
  var idTeacher = 0;
  this.createPerson = function(type, name) {
    var person;

然后使用控制台,运行这些行。

var s = new School();
s.createStudentAndTeacher(); // john
s.createStudentAndTeacher(); // bob
s.persons[0] // id 0:john
s.persons[1] // id 1:bob