Creating A Class Constructor

When using our framework, we will have a real constructor which JavaScript will call when the new operator is used, and a chain of pseudo-constructors which are unique to each class or base class. The real constructor for a class will be generated by the framework. It will call init, which our class inherits from XObject. As we saw in the previous page, init will call our chain of pseudo-constructors. For class Shape, the real constructor will look like this.

function Shape() {
    this.init(arguments);
}

There are several possible ways to create this constructor. One approach is to return a function from inside a function. The buildConstructor function in the following example does that.

buildConstructor: function() {
    return function() {
        this.init(arguments);
    }
}

Another approach is to use eval. You have probably been warned not to use eval, and that is usually good advice. A better way to word this might be "eval should be used rarely if at all" (borrowing from the sage advice about goto from Kernighan & Ritchie's The C Programming Language). Eval has its place, but it is frequently abused. It should be the last arrow drawn from your quiver, not the first. It is this author's opinion that this is one of the few situations where eval is appropriate. Assuming className contains the name of the class we are declaring, we would use eval like this.

eval("var newClass = function " + className +
     "(){this.init(arguments);}");

This code results in the variable newClass being created in our local scope and having its value set to the new function. One significant difference is this function will be named, while the function returned by buildConstructor is anonymous. When stepping through code using a tool such as Firebug, it is nice to see that our object is an instance of a specific class and not just Object. For that reason our framework will use the eval approach.

Next we will describe the mechanism for declaring a new class.