javascript中的构造函数和原型

时间:2013-12-20 20:59:05

标签: javascript

我很难学习构造函数和原型。我要做的就是在构造中添加2个新对象,然后显示对象的每个部分。在我的示例中,我想添加两个对象和控制台日志,每个名称,地址和gpa。

构造函数:

var Students = function(name, street, city, state, gpa) {
   this.student = {
      name: name,
      address: {
         street: street,
         city: city,
         state: state
      },
      gpa: gpa};
   this.array = [];
   this.array.push(this.student);
};

Students.prototype = {
   init: function(name, street, city, state, gpa) {
      this.student = {
         name: name,
         address: {
            street: street,
            city: city,
            state: state
         },
         gpa: gpa
      };
      this.array = [];
      this.array.push(this.student);
      console.log(this.array);
   },
   test: function() {
      console.log(this.array);
      for (i = 0; i < this.array.length; i++) {
         i = i % this.array.length;
         var studentTotal = 0;
         //This will loop through gpa array
         for (j = 0; j < this.array[i].gpa.length; j++) {
            studentTotal += this.array[i].gpa[j];
         }

         this.array[i].myAvg = studentTotal / this.array[i].gpa.length;
         this.array[i].gpaAverage = this.array[i].myAvg;
         console.log("Name: " + this.array[i].name);
         console.log("Address: " + this.array[i].address.street + ' ' +
                 this.array[i].address.city + ' ' +
                 this.array[i].address.state);
         console.log("GPA: " + this.array[i].gpa);
         console.log("Average: " + this.array[i].gpaAverage);
         console.log(new Date());
      }
   }
};

main.js:

var stud1 = [
   new Students(
           "Walker",
           '123 South Drive',
           'Sarasota',
           'FL',
           [
              3.0,
              3.4,
              3.8
           ]),
   new Students(
           'Christian',
           '5601 Pebble Beach Ln',
           'Sacromento',
           'CA', [
      2.5, 3.6, 3.8
   ])];

stud1.test();

1 个答案:

答案 0 :(得分:1)

你正在构建一系列学生。

var stud1 = [...]正在创建一个Students数组我想你最好将Students函数重命名为Student(因为它只构建一个学生)并将您的数组stud1重命名为studentArray,以使事情更容易理解。

然后,如果您想要对阵列中的所有学生拨打test(),请使用:

for(var i=0; i<studentArray.length; i++){
   studentArray[i].test();
}

在其他作品中,您尝试在数组上使用方法test(),并且数组没有该功能,学生也可以。

修改

考虑到您的评论,您可以制作另一个可以跟踪创建的学生的对象,并作为新学生的工厂。这封装了学生创建逻辑,并将所有学生列为学生构建逻辑,并让您进一步了解javascript对象的构建。

此外,让您的学生负责了解他们的平均GPA,因为您已经让他们跟踪他们的个人GPA。所以添加一个函数getAverageGPA(),然后每当你想要打印学生时,调用函数print(),打印出所有信息并获得他们的平均GPA。

由于您希望每次创建新学生时都这样做,请让学生工厂(School)为您执行此操作。

<强>学生: 学生班,其中包含有关学生的所有信息以及打印他/她的功能以及获得他们的平均GPA。

/**
 * Student Object
 * @param {String} name
 * @param {String} street
 * @param {String} city
 * @param {String} state
 * @param {Array} gpa
 * @returns {Student}
 */
var Student = function(name, street, city, state, gpa) {
   this.name = name;
   this.address = {
      street: street,
      city: city,
      state: state
   };
   this.gpa = gpa;
};
Student.prototype = {
   /**
    * Function to print the student and their average GPA
    * @returns {undefined}
    */
   print: function() {
      console.log("Name: " + this.name);
      console.log("Address: " +
              this.address.street + " " +
              this.address.city + " " +
              this.address.state);
      console.log("Average GPA: " + this.getAverageGPA());
   },
   /**
    * Function to find a students average GPA
    * @returns {Number}
    */
   getAverageGPA: function() {
      var avgGPA = 0;
      for (var j = 0; j < this.gpa.length; j++) {
         avgGPA = avgGPA + this.gpa[j];
      }
      avgGPA = avgGPA / this.gpa.length;
      return avgGPA;
   }
};

<强>学校: 持有学生并负责创建和打印它们的课程

/**
 * Object to encapsulate student creation while 
 * keeping track of all created students
 * @returns {School}
 */
function School() {
   /**
    * Array of all the students created so far
    * @type Array
    */
   this.createdStudents = [];
}
School.prototype = {
   /**
    * Function to add a student to the list of students
    * @param {Student} newStudent
    * @returns {undefined}
    */
   addStudent: function(newStudent) {
      this.createdStudents.push(newStudent);
      this.printScores();
   },
   /**
    * Function to create a student, add it to the list, and return it
    * @param {String} name
    * @param {String} street
    * @param {String} city
    * @param {String} state
    * @param {Array} gpa
    * @returns {Student}
    */
   createStudent: function(name, street, city, state, gpa) {
      var newStudent = new Student(name, street, city, state, gpa);
      this.addStudent(newStudent);
      return newStudent;
   },
   /**
    * Print out all the students and their scores
    * @returns {undefined}
    */
   printScores: function() {
      for (var i = 0; i < this.createdStudents.length; i++) {
         this.createdStudents[i].print();
      }
   }
};

主要 测试学生的创作是什么?

/**
 * The Factory to hold students
 * @type School
 */
var school = new School();

// Student created yourself that you have access to in main
var standAloneStudent = new Student(
        "Bob",
        "555 Nowhere street",
        "Timbucktue",
        "AL",
        [
           4.0,
           4.0,
           4.0
        ]);

// You can get the students GPA without going through the factory
console.log("My student's GPA is: " + standAloneStudent.getAverageGPA());

console.log("");

// How to add a student that you create yourself
school.addStudent(new Student(
        'Christian',
        '5601 Pebble Beach Ln',
        'Sacromento',
        'CA',
        [
           2.5,
           3.6,
           3.8
        ]));

console.log("");

// How to create a student through the factory
school.createStudent(
        "Walker",
        '123 South Drive',
        'Sarasota',
        'FL',
        [
           3.0,
           3.4,
           3.8
        ]);

// You can also get the students GPA through the school 
// (However, you may want to make a set instead of an array so you can key
// off of a student's name or maybe ID)
console.log("My student's GPA is: " + school.createdStudents[0].getAverageGPA());

这应该给你输出:

My student's GPA is: 4

Name: Christian
Address: 5601 Pebble Beach Ln Sacromento CA
Average GPA: 3.2999999999999994

Name: Christian
Address: 5601 Pebble Beach Ln Sacromento CA
Average GPA: 3.2999999999999994
Name: Walker
Address: 123 South Drive Sarasota FL
Average GPA: 3.4
My student's GPA is: 3.2999999999999994