0

Wrapping a JavaScript "class"?

Below is a simple "class" for displaying messages. It stores the output HTML div and then displays messages to it as needed.

It works fine. For readability, and encapsulation purposes, I'd like the components of the "class" in a container of sorts or a JavaScript object? What is the simplest way to to do this.

Or...is there a simple way to do this?

Currently the only container is the comments I've surrounded the code with.

/**
 *      Module  :       Model
 *      Name    :       -Message
 *      Input   :       div via the constructor
                        message type via display
 *      Output  :       TextStream via display to Control.sendInner
 *      Notes   :       Symmetric, client holds message location so needs extra variable
 */

var Message = function( div ) 
{
    this.div = document.getElementById( div ); 
};

Message.prototype.messages = 
{ 
    name:       'Please enter a valid name',
    email:      'Please enter a valid email',
    pass:       'Please enter passoword, 6-40 characters',
    url:        'Pleae enter a valid url',
    title:      'Pleae enter a valid title',
    tweet:      'Please enter a valid tweet',
    empty:      'Please complete all fields',
    empty_bm:   'Please complete all fields',
    same:       'Please make emails equal',
    taken:      'Sorry, that email is taken',
    validate:   'Please contact <a class="d" href="mailto:support@.com">support</a> to reset your password'
};

Message.prototype.display = function( type ) 
{
    Control.sendInner( this.div, this.messages[type] ) 
};      


/**      Message End        */

1 Answers1

1

If I understand you correctly, you can namespace your class using a self-calling function like so:

(function(window, undefined) {
    var foo = 0; //private variable accessible only to code within this scope

    //Your class definition:
    window.Message = function( div ) 
    {
        this.div = document.getElementById( div ); 
    };

    Message.prototype.message = //...

    //....
})(window);

But maybe i misunderstand the question...

The common way I create classes in JS is:

(function(window, undefined) {
    window.Class = function() {
        var private, variables, here;

        function privateFunc1(v) { here = v; }
        function privateFunc2() { return here; }

        return {
            publicSet: privateFunc1,
            publicGet: privateFunc2
        };
    }
})(window);

//Usage:
var c1 = new Class(), c2 = new Class();

c1.publicSet(true);
console.log(c1.publicGet(), c2.publicGet()); //output: true, undefined

EDIT Changed code a little for some usage

Chad
  • 19,219
  • 4
  • 50
  • 73
  • By not passing a value to the second parameter it will be the value `undefined` to ensure you always have a good reference to a value of undefined to compare to. The function wrapper places your code in its own scope. I cannot access anything within that scope, except what you assign to `window` for use in the global scope. Allowing you to have "private members" – Chad Dec 23 '11 at 17:38
  • Fundamentally there isn't a 1:1 relationship between declaration and invocation, at least in javascript- when you skip parameters on invocation, those parameters will be effectively sent as undefined. This pattern of passing the global scope in and having a parameter named undefined is a trick to ensure you A) have a global reference that is only looked up once, and B) have a clean/true representation of 'undefined' as the name undefined could be redefined as anything (although personally I think its a bit ott). – meandmycode Dec 23 '11 at 17:44
  • @stack.user.0 edited post to have my paradigm and usage info. – Chad Dec 23 '11 at 17:50
  • Thanks...good info...since you seem to get this...why in does js not have classes...people obviously write them...but the syntax is boggling in my mind. One thing I wonder is if you are executing a function as opposed to not in my simple version...is the extra proecessing time and syntax complextiy worth the added feature of privacy? Why the self execution as opposed to languages like C++ and PHP...I keep wondering if I should update my code-base 1000 ++ lines lines to this approach... hence the questions..thanks again –  Dec 23 '11 at 19:17
  • + here is another way to do it...http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects.......2nd answer down. –  Dec 23 '11 at 19:25
  • In terms of 'classes' javascript is more about prototypes, where class based languages have types on one side (with inheritance chains to reuse functionality) and instances of types.. javascript makes no distinction, you can create an object who's prototype is another object, that way- any properties that aren't available on that object, are looked up on the prototype object, or even the prototype objects prototype and so on. – meandmycode Dec 24 '11 at 14:05
  • ...just realized this is not best practice...all your classes are public(k) with the code your provided. They need to be name-spaced or made completely anonymous. When you tack on to window you make your "classes" public(k). Convention is to make libraries public(k)...i.e. window.jQuery....classes should be namespaced to a library. –  Jan 23 '13 at 01:42
  • @HiroProtagonist Debatable, if you have a collection of objects you want in global; obviously they should be under one namespace. If you have 1 class you want to export, you don't need to export a namespace and then put your one class under it; that is silly. – Chad Jan 23 '13 at 01:56