JavaScript Class Augmenter

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

Following my yesterday’s post about JavaScript inheritance without constructors, here’s another small class that exposes an easy to use API for inheritance and class augmentation. Below is the source code of the class, and the use cases are included in the distribution.

[sourcecode language=”javascript”]
(function() {
    "use strict";

   /*
    * @namespace AcidJs
    **/
    if(undefined === window.AcidJs) {
        window.AcidJs = {};
    }

   /*
    * @class Augmenter
    * @constructor
    **/
    function Augmenter() {}

    Augmenter.prototype = {

       /*
        * @method methods Inherit methods from one class to another
        * @pulic
        * @param superclass {Class}
        * @param subclass {Class}
        * @param members {Array} [optional] Array of methods that should be inherited. If not set, all superclass methods will be copied to the subclass
        **/
        methods: function(superclass, subclass, members) {
            var
                member;

            if(members) {
                for(var i = 0; i < members.length; i ++) {
                    member = members[i];

                    if(superclass.prototype.hasOwnProperty(member)) {
                        subclass.prototype[member] = superclass.prototype[member];
                    }
                }
            } else {
                for(member in superclass.prototype) {
                    if(superclass.prototype.hasOwnProperty(member)) {
                        subclass.prototype[member] = superclass.prototype[member];
                    }
                }
            }
        },

       /*
        * @properties properties Inherit properties from one class to another
        * @pulic
        * @param superclass {Class}
        * @param subclass {Class}
        * @param properties {Array} [optional] Array of properties that should be inherited. If not set all superclass properties will be copied to the subclass
        **/
        properties: function(superclass, subclass, properties) {
            if(properties) {
                for(var i = 0; i < properties.length; i ++) {
                    if(superclass.hasOwnProperty(properties[i])) {
                        subclass[properties[i]] = superclass[properties[i]];
                    }
                }
            } else {
                   for(var property in superclass) {
                       if(superclass.hasOwnProperty(property)) {
                           subclass[property] = superclass[property];
                       }
                   }
            }
        }
    };

    window.AcidJs.Augmenter = Augmenter;
})();
[/sourcecode]

Related Posts

Categories and Tags
Links

© 2006 - 2023 Martin Ivanov