Tech Journal Back to Tech Journal

Javascript: Two methods of defining static collections of methods and variables

/* Two ways to create "static"-method holding objects. Something like
* namespacing a set of methods. For instance, grouping all the methods for
* a lesson under "lesson", so you call them using "Lesson.method1",
* "Lesson.method2", etc.
*/

/* the object-singleton-way:
- simpler
- supports "this" for properties (although this didn't use to work, IIRC)
- requires JSON notation (the whole "{property: definition}" thing)
*/

var thingyone = {
    prop: 123,
    method: function() {
        alert(this.prop + ' ' + thingyone.prop);
    }
}

// Call the method:
thingyone.method();

/* The closure way
- less intuitive
- doesn't require JSON notation, only uses standard function/variable definition
- we define an anonymous function that contains all the defintion for the
object. This defines a closure. A closure is much like defining a scope. Since
inner scopes cannot be (easily) accessed from the outside, this lets you
"contaminate" the local namespace without overwriting anything.
- the important thing is the "();" at the end. That "executes" the function,
returning the value into the variable you're storing into. This is what's
difference about this approach from the origional JS classes of the 90's, where
you'd store a function like this into a variable, and then running that
variable (as a function) would create a new instance. We don't want to create
an instance, we just want to create a namespace, which is a collection of
functions grouped under a common name. Something like "Lesson.send_message(msg)"
- harder to give out public variables. This is actually a bonus, easier to
create private variable. ("harder" - you have to define them)
*/

var thingytwo = function(){
    // All declarations: public and private
    var hidden_prop = 345;
    var visible_prop = 987;
    function f(val) {
        return val+1;
    }
    function method() {
        alert(this.prop + ' ' + f(hidden_prop));
    }

    // Declare what's public:
    return {
        prop: visible_prop,
        method: method
    };
}();

// Call the method
thingytwo.method();
Last updated on 2008-03-20 15:39:21 -0800, by Shalom Craimer

Back to Tech Journal