Performance Test and Idea: Initialize a widget I want to extend an app object with a widget that initializes itself immediately.

Immediately-Invoked Function Expression:

var app = {};

(function() {
  app.widget = {
    init: function() {
      return true;
    }
  };

  app.widget.init();
}());


Immediately-Invoked Object Expression:

var app = {};

({
  init: function() {
    app.widget = this;

    return true;
  }
}.init());


Please take a look: http://jsperf.com/iife-vs-iioe
Code is not just about performance. You have to check for maintainability, scalability and readability as well.

With regards to the way code is written, I'd favor the first method because it's the module pattern and is a common convention. The second one is too full of brackets and the object notation, though flexible, is nasty especially when you forget the commas.

For extendability, I suggest you build a base set of helper functions to facilitate module loading and phase handling. Here are potential events that you might want to hook on events:


when the DOM is ready (DomContentLoaded)
when everything is loaded (window.onload)
when the page is unloading (window.onunload and onbeforeunload)
when the widget is loaded into the library
when the widget is unloaded/removed
when the widget is first run (init)
and so on...


Also, I suggest the following style of extension since:


It creates a single local scope for your widget to operate and share. You have the so called "private sandbox".
Objects are provided as an interface to attach stuff like public methods/properties, handlers and stuff. Whatever attached will be collected by your framework, sorted and executed accordingly.
It's simple and readable!


Here's a sample of a widget:

//assumung app is your framework namespace
app.addWidget('WeatherWidget',function(handles,publicStuff){

  //your local scope
  var foo = 'bar';

  function baz(){console.log('bam');}

  //handles and public are your interfaces
  //in this example, handles will be used to collect your event handlers

  handles.init = function(){/*run on init*/};
  handles.documentReady = function{/*run on DOM ready*/};

  publicStuff.getBar = function(){return foo;}

});