Extending objects (MooTools)
Black Ninja is killing Bob
by Piotr Zalewa
HTML
<div id='result'></div>
CSS
#result {
margin-top: 10px;
color: navy;
font-weight: bold;
font-size: 11px;
font-family: Helvetica, Tahoma, Arial;
}
JavaScript
var printData = function(obj) {
new Element('p',{
'text': "{name} ({age}) - energy: {energy}, alive: {isAlive}".substitute(obj)
}).inject('result','bottom');
};
// ------------------------------------------
var Human = new Class({
initialize: function(name, age){
// this will be run after instantiating an object
this.name = name;
this.age = age;
},
isAlive: true,
energy: 1,
eat: function(){
this.energy++;
},
});
// -------------------------------------------
var Ninja = new Class({
Extends: Human, // take whole Human prototype and add following
initialize: function(side, name, age){
this.side = side;
// call initialize from Human's prototype
this.parent(name, age);
},
energy: 100,
attack: function(target){
this.energy = this.energy - 5;
target.isAlive = false;
}
});
var bob = new Human('Bob', 25);
var blackNinja = new Ninja('evil', 'Nin Tendo', 'unknown');
printData(bob);
printData(blackNinja);
blackNinja.attack(bob);
printData(bob);
printData(blackNinja);