Saturday, August 28, 2010

Prototypes in JavaScript

Programmer Question

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?



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails