Over a million developers have joined DZone.

A JavaScript class pattern that starts with a function

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

There are too many JavaScript class patterns and inheritance APIs out there. Here is another one. The twist: Its core construct is a function, not an object literal.

Example usage:

    var MyClass = function () {
        this.count = 0;
        myMethod: function() {
            // ...
        CONSTANT: 123,
We make use of the fact that ECMAScript 5 allows trailing commas in object literals. The class definition starts with a function expression (a function declaration does not allow you to invoke methods) and then invokes methods on it to extend a superclass, add methods and add class properties.

This is the code that makes the above work:

    (function() {
        function copyOwnTo(source, target) {
            Object.getOwnPropertyNames(source).forEach(function(propName) {
                Object.defineProperty(target, propName,
                    Object.getOwnPropertyDescriptor(source, propName));
            return target;

        Function.prototype.extends = function (superClass) {
            var thisProto = Object.create(superClass.prototype);
            // At the very least, we keep the "constructor" property
            // At most, we preserve additions that have already been made
            copyOwnTo(this.prototype, thisProto);
            this.prototype = thisProto;
            return this; // enable chaining

        Function.prototype.proto = function (protoProps) {
            copyOwnTo(protoProps, this.prototype);
            return this; // enable chaining

        Function.prototype.class = function (classProps) {
            copyOwnTo(classProps, this);
            return this; // enable chaining
Note: This pattern is more a proof of concept than something I would use in practice. But I like that this kind of thing can be done in JavaScript.

Related reading:

  1. Class Definition Pattern Using Object Extension Literals” by Allen Wirfs-Brock [inspiration for this blog post]


From http://www.2ality.com/2011/10/class-pattern.html

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}