The first method is for creating an object that you only ever intend to have one of. It's for singletons. It creates the student1 object directly.
The second method is a constructor function. Constructor functions can be used again and again to create as many of these objects as you need.
By convention, constructor functions should be initially-capped (e.g., Student rather than student), like JavaScript's own objects (Date, RegExp, ...).
You could use the JavaScript prototype chain so that all of the Student objects use the same dispInfo function (with different this values) rather than creating a dispInfo for every object:
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+");
As of ES5 (and this is possible with "shims" as well, for older browsers), you don't have to use a constructor function to have objects that share a prototype, you can use Object.create to do that. I prefer constructor functions, but you can also use builder functions:
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+");
Note that we don't use new with builder functions, just with constructor functions. (It's usually harmless if you did, but it's unnecessary and misleading to anyone reading the code, so you don't want to.)
Or you don't even need the builder function in that simple case, you can just use Object.create directly, but it's a bit cumbersome because if you pass in property descriptors (the second argument), each one has to be an object describing the property, not just a value for it (there's a good reason for that), so you have to do {value: "the value"} (of course, you might want to specify other things about the property, like whether it's enumerable, etc.):
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+"}
});
Personally, I prefer constructor functions, but the great thing about JavaScript is that it supports multiple styles of programming, including ones where things like builders or using Object.create directly are more appropriate.