第一种方法是创建一个您只打算拥有一个的对象。这是给单身人士的。它直接创建student1 对象。
第二种方法是构造函数。构造函数可以反复使用,根据需要创建任意数量的对象。
按照惯例,构造函数最初应该是有上限的(例如,Student 而不是 student),就像 JavaScript 自己的对象(Date、RegExp、...)一样。
您可以使用 JavaScript 原型链,以便所有 Student 对象使用相同的 dispInfo 函数(具有不同的 this 值),而不是为每个对象创建一个 dispInfo:
function Student (a, b, c) {
this.name = a;
this.course = b;
this.grade = c;
}
Student.prototype.dispInfo = function(){
return this.name + ' has an ' + this.grade;
};
var s1 = new Student("Mary", "Algebra", "A");
var s2 = new Student("Joe", "Classical Sculpture", "B+");
从 ES5 开始(对于旧版浏览器,“shims”也可以做到这一点),您不必使用构造函数来拥有共享原型的对象,您可以使用 Object.create 来做到这一点.我更喜欢构造函数,但你也可以使用 builder 函数:
var StudentPrototype = {
dispInfo: function(){
return this.name + ' has an ' + this.grade;
}
};
function BuildStudent(a, b, c) {
var student = Object.create(StudentPrototype);
student.name = a;
student.course = b;
student.grade = c;
return student;
}
var s1 = BuildStudent("Mary", "Algebra", "A");
var s2 = BuildStudent("Joe", "Classical Sculpture", "B+");
请注意,我们不将new 与构建器函数一起使用,仅与构造函数一起使用。 (如果你这样做通常是无害的,但它对任何阅读代码的人来说都是不必要的和误导,所以你不想这样做。)
或者在那种简单的情况下你甚至不需要builder函数,你可以直接使用Object.create,但这有点麻烦,因为如果你传入属性描述符(第二个参数),每个必须 是描述属性的对象,而不仅仅是它的值(这是有充分理由的),所以您必须这样做 {value: "the value"}(当然,您可能想要指定属性的其他内容,例如是否为enumerable 等):
var StudentPrototype = {
dispInfo: function(){
return this.name + ' has an ' + this.grade;
}
};
var s1 = Object.create(StudentPrototype, {
name: {value: "Mary"},
course: {value: "Algebra"},
grade: {value: "A"}
});
var s2 = Object.create(StudentPrototype, {
name: {value: "Joe"},
course: {value: "Classical Sculpture"},
grade: {value: "B+"}
});
就个人而言,我更喜欢构造函数,但 JavaScript 的优点在于它支持多种编程风格,包括像构建器这样的东西或直接使用 Object.create 更合适。