Closures is a well known methodology to have public and private variables under JavaScript objects(in my opinion I think we exploit the closure technology). After spending some long time Mootools class module (I simply love it), PrototypeJS, JS.Class , and Dojo I asked myself; why can’t I have same JSON styled public, private structure? The exquisite way I used to do “this.privateVariableName” in Java or C++ was still not available by any of libraries (at-least the ones I mentioned); due the constraint that if we introduce anything in this structure, it will be accessible like any public property. As an example:
var Klass = function(){
this.x = 'hello';
};
var v = new Klass();
v.x; // gives me hello
So I spent some time hacking around, and I finally came up with a sleek hack to get the job done.
By exploiting Function.prototype.apply one can easily bind any arbitrary object to a method. So for each public method I can bind an object that contains both public and private data. After spending time, and putting my head into problem I finally came up with my own solution (For the time being I’ve named it OOrJa abrivating Object Oriented Javascript).
Since code is pretty immature yet, I know there is a long journey ahead before it really becomes stable and robustly usable.
Below is a sample code demonstrating a proof of concept about how simple and elegant code can look:
//Animal base class
var animal = Class({
Init: function(){
console.log('animal');
},
Public: {
eat: function(){
console.log(this.name+' eats');
this.name = 'animal';
},
name: 'animal',
walk: function(){
this.pwalk();
}
},
Private: {
pwalk: function(){
console.log(this.name+' walks');
}
}
});
//Dog derived class from animal overriding eat
var dog = Class(animal, {
Init: function(){
console.log('dog');
},
Public: {
eat: function(){
console.log(this.name + ' eats');
this.walk();
},
name: 'dog'
}
});
//Hound inherited from dog provides a new method howl
var hound = Class(dog, {
Init: function(){
console.log('hound'); // log constructor
},
Public: {
howl: function(){
console.log(this.name+" howls"); // log name
this.eat();
}
}
});
var dh = new hound(); // logs animal, dog, hound
dh.howl(); // Logs dog howls, dog eats, animal walks
Sweet. It follows the perfect C++ styled inheritance, since variable name is both in dog and animal class, each one of them creates it’s own context, hence the output is dog eats, and then animal walks (since dog class has no implementation of walk it inherits it from the parent class animal; and under animal class the name contains value “animal”).
Based on feedback and the taste of my own food (ya I always use my own code) I am looking forward to improve it.
Design by Simon Fletcher. Powered by Tumblr.
© Copyright 2010