Loading ...
Sorry, an error occurred while loading the content.

Re: [jslint] didactic example for clean JS

Expand Messages
  • Klemen Slavič
    Hello, While I don t think there s a one paradigm to rule them all, I can testify to the elegant extension methods that jQuery employs in its plugin
    Message 1 of 2 , Jul 9, 2008

      While I don't think there's a "one paradigm to rule them all," I can testify to the elegant extension methods that jQuery employs in its plugin authoring guidelines.

      Basically, a jQuery object instantiated using a selector is a DOM result set with enriched methods, like iteration. A jQuery plugin extends its functionality by extending its prototype by using code like this:

      jQuery.fn.myPlugin = function(options) {
        // iterate over each element and return the same result set
        return this.each(function() {
          /* do something with the single element */

      See http://docs.jquery.com/Plugins/Authoring for more details.

      I know, it's not very helpful for general Javascript coding practices, but I think it illustrates a well-defined way to managing and extending existing functionality. A lot can be learned by writing plugins for jQuery and studying its code base.

      I would recommend reading up Crockford's articles (http://javascript.crockford.com/) to better understand the language itself. Closures are the alpha and omega when it comes to widgets, since they need to be isolated from each other and from other code as much as possible for them to be able to be portable.

      Stuff like creating objects with quasi-private methods using closures enables such coding practices:

      var MyObject = function() {
        var myPrivateMethod = function() { /* ... */ };
        var myPrivateVariable = "some value";
        var myPublicMethod = function() { /* ... */ };
        var myPublicVariable = "some other value";
        return {
          someMethod: myPublicMethod,
          someVariable: myPublicVariable

      var a = MyObject();

      When calling a.someMethod(), you'll actually be calling the function inside the closure and someMethod() will be able to call myPrivateMethod() within its scope when it's executed like it is above. From the outside, though, you won't be able to call myPrivateMethod() (well, unless you use Firefox's eval(code, scope) - then you could bypass this).

      Executing code without creating any global objects is also possible:

      (function() {
        var a = 3;

      alert(a); // displays "undefined"

      There are also examples on how to use closures for event handlers, effectively binding values to the function being executed.

      Anyhoo, I've been verbose enough - probably best if you head to the provided URLs and start looking up the terms I've been liberally tossing around this post.


    Your message has been successfully submitted and would be delivered to recipients shortly.