Revealing Prototype Pattern and Scoping

by laustdeleuran

JavaScript

/*
First we create our "Class", and name it thoroughly to enable .constructor calls.
This function is, besides being the Class itself, also the function that is run whenever an instance of the Class is instanciated. To  keep our code in one spot, we simple make this call a construct function on itself.
*/
var Klass = function Klass () {
    return this.construct.apply(this, arguments);
};
/* 
Now we define our prototype. This is basically the collection of private and public methods and variables that every instance of our class will have available
*/
Klass.prototype = (function () {
    var construct, privath, // public methods
    instances, // private vars
    publich, privathWrap, privathWrapWithScope; // public methods
    
    instances = 0;
    
    /*
    Constructor
    */
    construct = function () {
        var scope = this; // This is our instance
        
        scope.value = 0;
        
        instances += 1;
        console.log('Klass initiated, instance number ' + instances);
        
        scope.instanceNo = instances;
    };
    /*
    Public
    */
    publich = function () {
        console.log('publich', this, arguments);
    };
    /*
    Private
    */
    privath = function () {
        console.log('privath', this, arguments);
    };
    /*
    privathWrap
    */
    privathWrap = function () {
        privath(arguments);
    };
    /*
    privathWrapWithScope
    */
    privathWrapWithScope = function () {
        privath.apply(this, arguments);
    };
    
    /*
    Now we reveal all our public methods to the prototype, to enable these to be available on every instance
    */
    return $.extend(Klass.prototype, { // We use jQuery.extend to retain the original prototype object members
        construct: construct, // We most reveal this to allow the trick we made with the constructor when creating the Class to work
        publich: publich, 
        privathWrap: privathWrap,
        privathWrapWithScope: privathWrapWithScope
   ...