Monday, September 08, 2008

Public / Private Methods - Inheritance (JS)

There are several ways to determine what and how to configure a public methods in JavaScript:


* = Public Method/Var, * = Private Method/Var

One way:


function Company(){

 var name = null;

 return {
   setName: function(n){
    name = n;
   }
,

   getName : function(){
    return name;
   }

 }
}

This is the way "Duglas Crockfor way" implements public methods, but I like more to see all the methods inside a unique container (as in Java or C++) and determine what is public or private with a simple distinguish symbol, in this case The "this" (for public).

Second way (the one I prefer):


function Company(){

 var name = null;

 this.setName = function(n){
   name = n;
 }


 this.getName = function(){
   return getUppercase(name);
 }


 function getUppercase(str){
   return str.toUpperCase();
 }

}

This way the object (Company) remains the same instance of a Company type and not as the example before, while returning a new object, the instance of the object is not Company.

Also for me is more clear to show with "this" the Public Methods.

Remember that the Private Methods are also static, and private (Static) methods cannot call public (non-static) ones.

Object Oriented - Inheritance (JS)

There are a number of possibilities for implementing Inheritance in JavaScript.
I prefer using the Call or Apply method because it's simple to implement, the API is very clear and the code looks nice.

It works the following way:

Api:

var dog = new Dog(1);
dog.setName("Lola");
dog.setAge("3");

animal.js

function Animal(id){

 this.id = id;
 this.name;
 this.age;

 this.getId = function(){
   return this.id;
 }

 this.setName = function(name){
   this.name = name;
 }

 this.getName = function(){
   return this.name;
 }

}

dog.js

function Dog(id){

Animal.apply(this, arguments);

 this.saySomething = function(){
   return "Wow, wow wow " + this.getName() + " woof " + this.getAge() + " wow woof.";
 }
}