viernes, 14 de diciembre de 2012

Simple Herency in Javascript

//May be, I'm wrong and there is a better way 
//for getting simple herency in javascript
function Thing(name){
 this.color = 'black';
 this.name = name;
}

Thing.prototype.sayName =  function(){
 alert('Thing My name is: ' + this.name);
}

Thing.prototype.sayColor = function(){
  alert('My color is: ' + this.color);
}

function Animal(){
 Thing.call(this, "Floppy"); //<--- herency properties with a parameter
 this.age = 12;
}

Animal.prototype = new Thing();    //<--- set herecy functions by prototypes 
Animal.prototype.constructor = Animal; //<-- set constructor of the object Animal

Animal.prototype.sayAge = function(){
  alert('Animal, my age is: ' + this.age);
}

Animal.prototype.sayName =  function(){ //<--- override the mother's function sayName
  alert('Animal My name is: ' + this.name);
}

var dog = new Animal();
dog.color = 'red';
var phone = new Thing('htc');

alert(' phone color: ' + phone.color + ' phone name: ' + phone.name);
alert('dog, age: ' + dog.age + ' dog color: ' + dog.color + ' dog name: ' + dog.name);
phone.sayName();
phone.sayColor();
dog.sayName();
dog.sayAge();

No hay comentarios:

Publicar un comentario