2

I once read that it's good practice to enclose your whole script inside a self invoking function instead of just directly writing it to the document.

eg. Do this:

(function ()
{
  //code here

})():

Although when I do this, it's more difficult to debug because all variables are outside of scope, and also I can't create objects from external classes. I remember the source saying that this should be done as a security measure. Is this good practice? If so, why?

hsbsid
  • 301
  • 1
  • 2
  • 10
  • 2
    It avoids polluting the global scope. You can still debug it by using... well, the debugger. Not sure what you mean about "external classes", the IIFE has access to everything the "bare" code would. – Dave Newton Jun 14 '15 at 01:38
  • http://stackoverflow.com/questions/18203897/a-self-invoking-anonymous-function-expression – meder omuraliev Jun 14 '15 at 01:42
  • @DaveNewton I keep my classes inside a separate document. When I try to create an instance of that class in the main script (self-invoked script) it says that the class is undefined. – hsbsid Jun 14 '15 at 02:04
  • @hsbsid unless the classes in the separate document are scoped in a self-invoking anonymous function, that claim doesn't really make sense. The idea is to expose anything that needs to be accessed by other components to the global scope by doing ``window.MyClass = MyClass;`` or something similar inside the self-invoking function. – Patrick Roberts Jun 14 '15 at 02:41
  • @PatrickRoberts should the `window.MyClass = MyClass;` be added to the main script? – hsbsid Jun 14 '15 at 02:59
  • @hsbsid I don't mean that literally, unless you actually have a function called ``MyClass``, but if you want other scripts to be able to access the class outside the self-invoking anonymous function, then yes, you should do that. – Patrick Roberts Jun 14 '15 at 03:02

0 Answers0