There is a lot of material out there explaining how prototypes work. In your example above, you are declaring two constructors that are equivalent. That is, you could create objects of type 'Student' out of your two constructors.
For example, I can either do:
function Student() {
// initialization
}
var pascal = new Student();
Or I could do
var Student = function(){
// initialization
};
var pascal = new Student();
The result is the same.
Now, these constructors have a prototype object. They get one by default if you do not assign one to them. For instance, in either case I can do:
Student.prototype.getName = function(){
return this.name;
};
And then any of my student instances could something like:
pascal.getName();
However, you could create you own prototype objects and assign them directly, in case you would like to expose something through them to all instances of a given constructor. For instance.
You could say that the prototype of Student is another object.
Student.prototype = {
takeExam: function(){
//define take exam
},
constructor: Student
};
And now this synthetic object is the prototype of the Student constructor.
Or you could even define a type hierarchy with this, like in this example:
function FlyingThing(){ };
FlyingThing.prototype.fly = function(){
//fly
};
function Bird(){ }
Bird.prototype = new FlyingThing();
Bird.prototype.walk = function(){
//walk
};
Now, every instance of Bird can both fly and walk.
Now, it is important to distinguish between a constructor prototype and and instance prototype. As I have already shown, you have direct access the constructor prototype and you can easily change that, add new stuff to it, or change it in anyways you find appropriate.
When an instance is created for a given constructor, it gets assigned a prototype object based on the constructor you used to create it. That prototype is not so readily accessible. That prototype is the one that JavaScript will use in property lookups.
If you want to know what is the prototype of a given instance object you need to use the Object.getPrototypeOf
and Object.isPrototypeOf
methods as shown in other answer.
The prototype of an instance of Student
should logically be the Student.prototype
object that you defined for the Student constructor.