Self-Executing Functions in JavaScript

I’ve been steadily migrating my JavaScript assets to use self executing functions (and more recently literals) as they are a good way to enforce scope on variables and make your JavaScript more readable.

The examples below show the difference between implementing a self-executing function and using literals.

I have found that on most browsers (except Safari), there is a considerable performance win when using literals.

Creating a module via a self-executing function

obj = (function () {

  var _privateVar;
  var publicVar;

  function setPrivateVar(value) {
     _privateVar = value;
  }

  function getPrivateVar(value) {
    return _privateVar;
  }
  
  // api
  return {
    publicVar: publicVar,
    setPrivateVar: setPrivateVar,
    getPrivateVar: getPrivateVar
  }
}());

 Creating a module via object literals

obj = {
  _privateVar: undefined,
  publicVar: undefined,

  setPrivateVar: function setPrivateVar(value) {
    obj._privateVar = value;
  },

  getPrivateVar: function getPrivateVar(value) {
    return obj._privateVar;
  }
};

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.