Javascript – Self-referencing anonymous closures: is JavaScript incomplete

javascript

Does the fact that anonymous self-referencing function closures are so prevelant in JavaScript suggest that JavaScript is an incomplete specification? We see so much of this:

(function () { /* do cool stuff */ })();

and I suppose everything is a matter of taste, but does this not look like a kludge, when all you want is a private namespace? Couldn't JavaScript implement packages and proper classes?

Compare to ActionScript 3, also based on ECMAScript, where you get

package com.tomauger {
  import bar;
  class Foo {
     public function Foo(){
       // etc...
     }

     public function show(){
       // show stuff
     }

     public function hide(){
       // hide stuff
     }
     // etc...
  }
}

Contrast to the convolutions we perform in JavaScript (this, from the jQuery plugin authoring documentation):

(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

  };

})( jQuery );

I appreciate that this question could easily degenerate into a rant about preferences and programming styles, but I'm actually very curious to hear how you seasoned programmers feel about this and whether it feels natural, like learning different idiosyncrasies of a new language, or kludgy, like a workaround to some basic programming language components that are just not implemented?

Best Answer

I suppose everything is a matter of taste, but does this not look like a kludge, when all you want is a private namespace? Couldn't JavaScript implement packages and proper classes?

Most of the comments are argue against the myth that "prototypes are poor man's classes", so I'll just repeat that prototype-based OO isn't inferior in any way to class-based OO.

The other point "a kludge when all you want it a private namespace". You might be surprised to know that Scheme uses the exact same kludge to define scopes. That didn't stop from becoming the archetypal example of lexical scoping well done.

Of course, in Scheme, the 'kludge' is hidden behind macros....

Related Topic