Monday, September 08, 2008

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.";
 }
}

0 Comments:

Post a Comment

<< Home