Tag: objects

  • A simple(r) approach for class-based OOP in JavaScript.

    Like others before me, I found JavaScript’s prototype-based OOP support – while very powerful – quite cumbersome in some situations where I needed a certain structure or hierarchy of objects, situations in which one quickly comes to the conclusion that the best answer would be the concept of a Class.

    However, while I am well aware that the web is filled with various implementations of classical (i.e. class-based) object orientation in JavaScript, I can not help the feeling that they are over-engineered and over-complicated without need, quite often attempting to provide more functionality than is actually necessary. In short, I don’t feel they’re “classical” at all.

    This is why I started working on my own implementation of classical OOP  in JavaScript, which is shown below. Currently this is only a proposal, although I already started using it in one of my projects. Anyway, let’s look at it first then I’ll try and explain how it works.

    The Code

    /** Class factory. */
    function Class(members) {
    
        // proxy constructor
        var Proxy = function() {
            for (var item in members) {
                this[item] = members[item];
            }
        };
    
        // proxy inheritance
        Proxy.prototype = (members.base || Class).prototype;
    
        // class constructor
        var Build = members.init || function() {};
    
        // class inheritance
        Build.prototype = new Proxy();
        Build.prototype.base = Proxy.prototype;
        Build.prototype.constructor = Build;
    
        // ready
        return Build;
    }

    That is all, and this little function can have a whole world of nifty consequences like deep inheritance or access to the super-class via this.base (and others). But here is what happens: the basic principle at work here is the Proxy object, which essentially, contains all the members of our new class (the ones that are passed to the Class factory function as the members parameter). (more…)