Javascript – the industry and community best practice for coding proper maintainable readable jQuery for a large codebase


Coming from a Ruby background, I'm used to writing all my code using classes with methods and such. I do know javascript quite well, but I'm new to jQuery and its best practices.

Obviously there are a million ways to simulate classes in javascript. But, what is the actual jQuery community REALLY using in the real world?

Specific examples would be ideal. Or links to real production code. Links to fictional ideal code would also be helpful.


Best Solution

This doesn't apply specifically to jQuery, but I like the object literal syntax for simulating classes in my own code.

I tend to often use something like this (simplified) framework:

var Widget = {



        // do stuff here that doesn't need to wait until the DOM is ready.

        // Inside an anonymous function (such as the 'click' handler below),
        // 'this' loses its scope and no longer refers to the widget object.
        // To retain a reference to the widget object, assign 'this' to a
        // variable. I use an underscore... some people like 'self':
        var _ = this;

        // when the DOM is ready, run the init "method":
            _.init(); // the underscore now refers to the widget object



        var _ = this;

        // whenever a <p class="noisy"> element is clicked, call makeNoise()



        alert(this.sound); // alert 'bleep'




Edit: More information on use of the 'this' keyword, noted above: