Jul 15th 2010 × protecting private class methods in mootools
This is a bit of a sore topic as it is often being asked by people on forums and sites like Stack Overflow. Essentially, javascript does not offer a meaningful way to protect methods from being called directly. Come to think of it, neither does mootools–at least not officially.
However, there is a private API (meaning, not supported) that allows you to do it – its via .protect()
Here is a simple ninja class that shows how we can prevent our ninja from being killed directly without receiving damage first:
var ninja = new Class({
Implements: [Options,Events],
options: {
startHealth: 10,
name: "Bruce",
surname: "Lee"
},
initialize: function(options) {
this.setOptions(options);
this.health = this.options.startHealth;
this.alive = true;
},
heal: function(points) {
if (!this.alive)
return;
this.health += points || 1;
},
hurt: function(points) {
if (!this.alive)
return;
this.health -= points || 1;
if (this.health <= 0)
this.die();
},
die: function() {
this.alive = false;
this.fireEvent("death", this); // let everyone know
}.protect() // protected method
});
var bruce = new ninja({
onDeath: function() {
// default handler when death occurs
alert(this.options.name + " " + this.options.surname + " has passed away.");
}
});
bruce.hurt(5);
try {
// not allowed to kill ninja directly, need to hurt it instead
bruce.die();
}
catch(e) {
alert("the ninja lives!");
alert(e);
}
// now hurt it more so it dies anyway
bruce.hurt(5);
The .protect() will cause any attempts to call .die on the instance directly to throw an exception and fail. Once again - although this works with mootools 1.2.4 and on mootools 1.3 nightly build, it's not documented and is unsupported - don't rely on this too much (may disappear in mootools 2.0, perhaps). Still, a nice feature to have at hand, certainly
Check the jsfiddle to play with it some more: http://www.jsfiddle.net/dimitar/jQW5q/




