Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created May 9, 2010 03:36
Show Gist options
  • Save ryanflorence/394932 to your computer and use it in GitHub Desktop.
Save ryanflorence/394932 to your computer and use it in GitHub Desktop.
Abstract MooTools Class Basics
var Human = new Class({
initialize: function(name, age){
this.name = name;
this.age = age;
},
isAlive: true,
energy: 1,
eat: function(){
this.energy++;
}
});
// usage
var bob = new Human('Bob Ross', 50);
bob.energy; // 1, from the prototype
bob.eat(); // assigns bobs own energy to 2
bob.energy; // 2, prototype not checked anymore
bob.name; // Bob Ross, nothing to do with prototype
var Ninja = new Class({
Extends: Human,
Implements: [Warrior],
initialize: function(side, name, age){
this.side = side;
this.parent(name, age);
}
});
var blackNinja = new Ninja('evil', 'Nin Tendo', 'unknown');
blackNinja.eat(); // inherited from Human
blackNinja.attack(bob); // copied from Warrior
bob.isAlive; // false, bob never had a chance
blackNinja.kills; // 1, from Warrior
var Samurai = new Class({
Extends: Human,
Implements: [Warrior],
side: 'good',
energy: 1000
});
// assuming #jack is an element
// and our samurai class takes
// a jQuery selector for the first
// argument in the initialize method
// instantiate a class instance
$('#jack').samurai(); // new Samurai('#jack')
// call a method
$('#jack').samurai('eat') // jack.eat()
// get a property
$('#jack').samurai('isAlive'); // jack.isAlive
// set a property
$('#jack').samurai('kills', 2); // jack.kills = 2
// chain stuff
$('#jack').samurai('attack', bob).animate().css();
var Warrior = new Class({
energy: 100,
kills: 0,
attack: function(target){
if (target.energy < this.energy){
target.isAlive = false;
this.kills++;
}
this.energy = this.energy - 5;
}
});
@eerne
Copy link

eerne commented May 9, 2010

@eerne
Copy link

eerne commented May 10, 2010

Nice example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment