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);
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);
Share
Improve this question
edited Dec 16, 2016 at 17:46
mu is too short
435k71 gold badges858 silver badges818 bronze badges
asked Dec 16, 2016 at 16:35
Carlos AzuajeCarlos Azuaje
1193 silver badges14 bronze badges
0
2 Answers
Reset to default 8Completely appropriate. That's monly 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 remend the use of IIFEs, as does Douglas Crockford - http://javascript.crockford./
... tho he advocates the parens should be inside the declaration (function(){ }())
It's neither more or less secure.
The disadvantage of an anonymous function when pared 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./a/2421949/4992551.