Skip to content Skip to sidebar Skip to footer

How Is This Javascript Pattern Called And How Do I Use It In The Right Way?

I have taken over an existing project which uses JavaScript in the following way. I would like to understand how/why this is done and get some more information on how to use it eff

Solution 1:

That is a JavaScript Object Literal or Singleton pattern. Here's a really basic example:

<script>var exampleObj = {

    settings : {
        'test' : 'example'
    },

    alertSettings : function(){
        alert(this.settings.test);
    },

    gotCha : function(){
        var self = this;
        $('body').animate({"background-color":"red"},2000,function(){
            alert(self.settings.test);
            self.alertSettings();
        });
    },

    init : function() {
        this.alertSettings();
        this.gotCha();
    }

}

exampleObj.init(); // triggers the events</script>

Init triggers the alertSettings() method and then gotCha(). You will notice that gotCha() redeclares this as self. That's because there is a function within a function inside gotCha() and this is limited (or scoped) to the function it is contained within. So the inner function refers to the self alias (or clojure) because the variable it wants to alert is in the outer function this.

Quick and dirty. I hope this helps. * Needs jQuery

Post a Comment for "How Is This Javascript Pattern Called And How Do I Use It In The Right Way?"