Posts Tagged ‘Javascript’

Namespace, Encapsulation in JavaScript

February 24th, 2010

I’ve had several discussion recently some of the more advanced features of JavaScript, such as functions as return values, namespaces, encapsulation, etc. In order to demonstrate some of these things, I contrived a simple example of a dependency injection tool.

Never mind that dependency injection is not really a relevant pattern in JavaScript or other dynamic languages. It just fit all the pieces I wanted to demo. The Rhino JavaScript engine was used to run and test the example.

For more on how this stuff works, check out Douglas Crockford’s JavaScript: The Good Parts

//ObjectMap namespace
var ObjectMap = function (){
    var that = this;

    that.container = function () {
        var registry = {};
        var fact = {};

        fact.register = function (name, constructor) {
            registry[name] = constructor;
        };

        fact.getObject = function (theType) {
            return registry[theType]();
        };
        return fact;
    }();

    return that;
}();

//Dog constructor, with encapsulated private name
var Dog = function () {
    var d = {};
    var name = "spot";
    d.getName = function () {return name;};
    d.setName = function (val) {name=val; return d;};
    d.speak = function () {return d.getName() + " barks";};
    return d;
};

//register Dog with the DI tool
ObjectMap.container.register("Dog", Dog);

//get and use an object function the DI tool
var munson = ObjectMap.container.getObject("Dog");
munson.setName("Munson");
print(munson.speak());

Javascript Scoping

November 24th, 2008

If you understand what’s going on when this runs, then you understand javascript scoping.

var x = 5;
alert(x);

function foo(){alert(x);var x = 10;alert(x);}

foo();
alert(x);

Javascript Objects and Hashes

October 23rd, 2008
Employee = {
  New: function(fname,lname,em) {
     return {
        first: fname,
        last: lname,
        email: em,
        displayName: function() {
          return this.last + ', ' + this.first
        },
        sig: function() {
          return this.displayName() + ' ' + this.email
        }
     }
   }
}
var tim = Employee.New('Tim', 'Hoolihan','tim@hoolihan.net')
tim.sig()

On the Rise, Fall, and Resurgance of Javascript

October 23rd, 2008

Douglas Crockford’s essay on Javascript’s history and resurgance is a great read, if you haven’t already read it.

- “Given the process that created JavaScript and made it a de facto standard, we deserve something far worse.”

tags: | categories: Programming, Web | no comments »