The global object and local variables

JavaScript’s global object is the container of all global variables. Any top-level variable of any compilation unit will be stored in the global object. The global object is one of the worst parts of JavaScript when it is not used correctly, as it can easily become bloated with unneeded variables and can be unknowingly abused by developers when JavaScript default behavior is heavily relied upon. Here are two examples of such misuse:

  • When running a simple code such as total = add(3, 4);, you are, in fact, creating a property named total in the global object. This is not a good thing for performance as you might keep a lot of variables on the heap while most of them are only required at a certain moment of an application's execution.
  • When neglecting to use the new keyword in order to create an object, JavaScript will execute an ordinary function call and will bind the this variable to the global object. This is a very bad thing, not only for security reasons, as it is possible to clobber other variables, but also for performance reasons as the developer might think that he is storing values in an object's properties while he is, in fact, storing these values in the global object directly, thus bloating the global object and storing these values in two different memory spaces if he already instantiated the desired object elsewhere in his code.

To use the global object efficiently, you should wrap all your variables in a single application object, apply functions to it as needed, enforce type verification within the functions that you are applying to the application object in order to make sure that it is instantiated correctly and access the global object by thinking of it as a sort of immutable object with a few side-effect functions that are the application objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset