In the JavaScript the same thing you can do in many different ways.
Consider the examples:
1:
function Circle(radius) {
return {
"r" : radius,
"area" : function(){
return Circle.pi * this.r * this.r;
}
}
}
Circle.pi = 3.14159;
var a = Circle(10);
alert(a.area());
2:
function Circle(radius) {
this.r = radius;
}
Circle.pi = 3.14159;
Circle.prototype.area = function(){
return Circle.pi * this.r * this.r;
}
var a = new Circle(10);
alert(a.area());
The second is better than first because we dont define the same function area for any instance of the Circle.
But lets consider
3:
function Circle(radius) {
return {
"r" : radius,
"area" : Circle.area
}
}
Circle.pi = 3.14159;
Circle.area = function(){
return Circle.pi * this.r * this.r;
}
var a = Circle(10);
alert(a.area());
Is there any reason to prefer second style instead of third? Or I misunderstood something at all?
I would definitely go with example 2. Neither example 1 or 3 make good use of JavaScript’s object-oriented features because:
this, you lose the identity of the class, i.e. you can no longer do checks likea instanceof Circle.