##Classical Inheritance emulation experiments in Javascript. the Second one
I've been experimenting different ways to emulate classical inheritance in javascript and I will daily publish insights about some experiments that I've been doing in the last months till I reach a stable and usable solution for this inexistent problem.
The Second one:
function Class(){}
Class.Extends = function(props){
var Parent = this;
var proto;
Parent['extending'] = true;
proto = new Parent();
delete Parent['extending'];
for (prop in props){
proto[prop] = props[prop]
}
function Class (){
if (!Class['extending'] && typeof proto.init == 'function'){
proto.init.apply(this,arguments);
}
}
Class.prototype = proto;
Class.prototype.constructor = Class;
Class.Extends = Parent.Extends;
return Class
}
This approach works well in 90% of the cases and emulates the Classical inheritance in a really elegant way. Different from the previous example this is not just an workaround. It has constructor manipulation (the init method) and takes care of the prototype so you can play with instanceof in the child classes.
var Food = Class.Extends({
init:function(){
this.food = Math.floor(Math.random()*10);
},
eaten:function(){
this.food = 0;
}
})
var Fish = Food.Extends({
init:function(){
this.food = Math.floor(Math.random()*10);
}
})
var Animal = Class.Extends({
init:function(){
this.hungry = 100;
},
eat:function(food){
if (food instanceof Food){
this.hungry = this.hungry - food.food;
console.log(this.hungry)
food.eaten();
}else{
console.log('this is not edible')
}
}
})
var Cat = Animal.Extends({
init:function(name){
this.name = name;
this.hungry = 100;
}
})
var anAnimal = new Animal; //init Animal
var steveTheCat = new Cat('Steve');
steveTheCat.eat(new Fish);
steveTheCat.eat(new Food);
anAnimal.eat(steveTheCat); //this is not edible
- Almost simple
- Lightweight
- Works in 90% of the cases
- Constructor control =]
- Poor Super access
- No interface protection