creating a jsolait class

Creating a class is very simple using jsolait. Issues known from JavaScript?'s way of handling inheritance through prototyping are taken care of by jsolait.

Let's create some class with a single method foo() and a single property bar. We add another class to our module that inherits from the first class and overrides foo(). To construct these classes jsolait's Class([name,] [BaseClass1, ... ,] scope) function is used:


Module("tutorial", "0.0.1", function(mod){
    
    mod.SomeClass=Class(function(publ, priv, supr){
        publ.__init__ = function(barVal){
            this.bar = barVal;
        };
        
        publ.foo = function(p1){
            return this.bar * p1;
        };
       
        publ.bar;
    });
    
    mod.SubClass = Class(mod.SomeClass, function(publ, priv, supr){
        publ.__init__ = function(a, b){
            supr.__init__.call(this, a * b);
        };

        publ.foo=function(p1){
            var v1 = supr.foo.call(this, p1);
            return v1 * 3
        };
    });   
 
});

Similar to modules a scope function is used to create a private scope for the class. There are at least 2 parameters passed to the scope function:

  • publ This represents the public interface of the class.
  • priv A string containing an ID which is safe for creating private instance properties.
  • [supr, supr2, ...] All additional parameters represent the base classes' public interfaces.

Now lets have a look at the body of our class. The first thing to notice is the publ.__init__() method. This method is the initialization method for an object and is called during instanciation. Everything that you would put in a constructor will go inside that method. You can also see that it is added to the publ object. Any method (e.g. foo()) or property (e.g. bar) which should be accessible by other objects should be added to the publ object.

Creating subclasses is not much different, just add any number of classes before the scope function when calling Class(BaseClass1, BaseClass2, ..., scope). (All lefthand classes will override any righthand class in terms of public interfaces and class methods.)

Inside the SubClass::__init__() and SubClass::foo() method you can see how a base class' method is invoked. It has the form supr.someMethod.call(this, param1, ...).

Once a class is created it behaves just like any other JavaScript class/constructor:


var tutorial = imprt("tutorial");

var obj = new tutorial.SubClass(3,4);

alert(obj.foo(3)); 

try the code above