4

If I wrap my script in an anonymous style function like when Compiling in Coffeescript is appropriate to manipulate the DOM?

  • What benefit does it have?
  • What problem does this have?
  • Is my code more secure?

(function() {

this.detect = function(){
  window.alert( "message" );

};

}).call(this);
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Carlos Azuaje
  • 109
  • 3
  • 13

2 Answers2

8

Completely appropriate. That's commonly known as an IIFE.

Benefits are:

  • You can avoid variable naming clashes by "working under a namespace" - naming variables and setting scope:

    (function ($, DOM, ultraSelector) {
    
         $(DOM).find(ultraSelector); // $ is always jQuery
    
    })(jQuery, document, 'mySelector');
    
    $ = false; // here $ is not jQuery anymore
    
  • Your variables stay managed under your scope, never globally acessible; and

  • You can 'use strict' safely knowing that only the code inside the IIFE will be affected:

    (function () {
    
         'use strict';
    
         globalVariable = true; // will throw error
         var scopedVariable = true; // only accessible inside this IIFE
    
    })();
    
    globalVariable = true; // will define a global variable
    var scopedVariable = true; // is not really scoped, since its scope is global
    

I would say its more secure, yes. At least your variables are not easily accessed via browser console.

I strongly recommend the use of IIFEs, as does Douglas Crockford - http://javascript.crockford.com/ ... tho he advocates the parens should be inside the declaration (function(){ }())

rabelloo
  • 376
  • 2
  • 5
0

It's neither more or less secure.

The disadvantage of an anonymous function when compared to a named function is that it is only called once (or once per parent function) as that block of code is read. It can't be called by name.

The advantage of an anonymous function as opposed to a named function would be shorter syntax.

But if the question is whether to use this anonymous function as a wrapper, I really don't see any advantage to it. It's just adding extra code.

EDIT: If your anonymous function were a little longer, and contained variables, I can see it being useful to avoid polluting the global scope with those variable names. But in your example, that's not the case. See this answer for discussion of how its useful for namespacing: https://stackoverflow.com/a/2421949/4992551.

Community
  • 1
  • 1
dave
  • 2,762
  • 1
  • 16
  • 32