I'm accustom to work with constructor-functions this way:
function Computer(ram) {
this.ram = ram;
}
// Defining a property of the prototype-
// object OUTSIDE of the constructur-
// function.
Computer.prototype.getRam = function() {
return this.ram + ' MB';
}
I define and initialize values within the constructor. Methods are attached upon the prototype-object outside the constructor-function.
Yesterday I've seen these technique:
function Car(maxSpeed) {
this.maxSpeed = maxSpeed;
// Defining a property of the prototype-
// object WITHIN the constructur-
// function.
Car.prototype.getMaxSpeed = function() {
return this.maxSpeed + ' km/h';
}
}
The method is defined within the constructor-function => Without creating at least one object the method doesn't exist.
What I always consider a bit weird concerning the first approach is that someone can call the method upon the constructor-function / -object. Then all properties which use the this-keyword return undefined. With the second technique an error is thrown.
What are the advantages and disadvantages of both techniques?
Which one should I prefer / avoid and for what reasons?