Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototypes in JavaScript

Tags:

javascript

oop

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?

like image 533
Dan Avatar asked Aug 28 '10 20:08

Dan


2 Answers

I would definitely go with example 2. Neither example 1 or 3 make good use of JavaScript's object-oriented features because:

  1. You duplicate method definitions in each instance.
  2. By returning a new object instead of using this, you lose the identity of the class, i.e. you can no longer do checks like a instanceof Circle.
  3. You give up the possibility of inheritance since you do not use prototypes.
like image 128
casablanca Avatar answered Sep 28 '22 11:09

casablanca


Is there any reason to prefer second style instead of third?

The third style is still wasting a small amount of space in order to store the association between the name area and the area function.

Also because you are returning a new Object from the {...} literal, instanceof Circle won't work.

The second is better than first because we dont define the same function area for any instance of the Circle.

Indeed, but it can sometimes be useful to define a new copy of each method—a copy that, thanks to closures, can know what object it is bound to. With traditional prototyping you only get the this context which is set from the object the caller retrieved it from, rather than bound to a particular object. The first way avoids the problems of this-retention in things like event handlers, at the price of some loss of efficiency.

like image 20
bobince Avatar answered Sep 28 '22 13:09

bobince