JavaScript Class Augmenter

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.

(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;
})();

Related Posts

14 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>