Javascript Closures

0

Category :

Douglas Crockford’s five part series on Javascript

Crockford shows a much nicer object creation strategy based on closures, which looks something like this:

var animalsApp = (function(){

    var new_animal = function(name) {
        var animal = {};

        animal.sayHello = function() {
            return "Hello, my name is " + name;
        }
        return animal;
    }

    var new_dog = function(name) {
        var dog = new_animal(name);

        dog.bark = function() {
            return "woof";
        }
        return dog;
    }

    var new_cat = function(name) {
        var cat = new_animal(name);

        cat.meow = function() {
            return "eeooowww";
        }
        return cat;
    }

    return {
        main: function(){
            var dog = new_dog("rover");

            console.log(dog.sayHello());
            console.log(dog.bark());

            var cat = new_cat("tom");

            console.log(cat.sayHello());
            console.log(cat.meow());
        }
    };
}());

animalsApp.main();

Using this technique we can create properly encapsulated objects. In the example above, our animalsApp only exposes a single function, main, new_animal, new_dog and new_cat are all private. The class definitions are very clear, any variables or functions defined in the constructor body are private and we only expose members that we explicitly attach to the object (dog.bark = function(){}).


my thanks to:
http://mikehadlow.blogspot.com/2010/12/javascript-defining-classes-with.html

0 comments:

Post a Comment