Search code examples
javascriptextjsextjs4

How to introduce class system similar to ExtJs


I was trying to solve this looking at the ExtJs code, but I don't get the magic that is happening there.

I'd like to recreate the Ext class behaviour, which can be stripped to two basic functions :

  • define
  • create

Define is used to reserve a namespace for the new class and save reference to class constructor (at least my debugging indicates this). Sample usage : Ext.define('Foo', {param: 1});

Create is used to instantiate the class which simply returns new object instance.

Now I wonder what should be stored in the 'define' step, because afaik constructor itself is not enough to instantiate an object ? (or am I wrong)

Has anyone seen any references to materials covering topic of class systems in javascript ?


Solution

  • Douglas Crockford has a good article about classical inheritance in JavaScript: http://www.crockford.com/javascript/inheritance.html

    Some pseudocode that I think works similar to what Sencha has in their Ext (although I think that you should take a look at proper implementation in link above first):

    //define takes class name (string) and definition(object)
    //definition in this case should have a method called constructor()
    
    var classes = {};
    
    
    classes.define = function(className, definition){
        classes[className] = definition;
    }
    
    //call create with class name and it will make a new class using that constructor
    classes.create = function(className){
       return new classes[className].apply(this);
    }
    
    classes.define('Hello',{name: "Pi" , game : "Tennis"});
    
    console.log(classes);
    
    classes.create('Hello');