Deny global links in javascript

I have a problem with the names of code variables conflicting with each other, i.e.

<script type="text/javascript">var a = "hello"; </script> <script type="text/javascript">alert(a);//this works, when I want 'a' not to exist </script> 

Are closures the only option?

Coming from a C # background, this is like building an unreferenced instance of a delegate and then calling it inline, which seems a bit messy

 (function(){var a = "hello";})(); (function(){alert(a);})();//yes! working as expected 
+4
source share
5 answers

Using the (immediately self-executing) function to create a new area is indeed a way.

This also has the advantage that you can ensure that certain variables have certain values. When using jQuery, the following is commonly used:

 (function($, window, undefined) { // ... })(jQuery, this); 

If you donโ€™t have a ton of functions, each of which has only one operator (as in your example), it is also perfectly readable.

+6
source

Yes, closing is your only option. In browsers, all JavaScript files fall into the same global area.

IIFE is a very common place in JavaScript; I would not call them messy.

+5
source

Javascript has only a scope of functions, unlike C #, which has a scope of a block. The following code is valid javascript and C #:

 var x = 2; while(true) { var y = 3; break; } //y is not accessible here in C#, but is in javascript 

The only way to create a new scope is to create and execute an anonymous function.

+2
source

In short, built-in material, then it is best to use a module template to create a closure and, therefore, emulate private variables.

 (function(){ var a.... })(); 

The best long-term approach is to use objects as namespaces.

 var NS = {}; NS.a = 1; 
0
source

Just to present a different perspective. You can write code without using closures and maintain a (possibly) safe area of โ€‹โ€‹the global variable.

  • Define one object to use as a namespace with a suitable unique name (for example, MyAppContext) that will have a global scope, and if you need to define global variables for use only in your application, attach them to this object.

    MyAppContext.apptitle = 'Application Name';

  • At the beginning of your script where you create MyAppContect , make sure it does not exist.

  • Make sure that all variables with a functional range use the var keyword, so you know that you are not referencing a global value.

Obviously, this approach poses a risk that you forget to define some of your function variables with var . JSLint can help you with this.

I am happy to cancel this answer if I start to cry, but I believe that this is an acceptable alternative approach to using closures. And hey! this is an old skool

I also agree that using closures is safer, but thought it might interest you.

0
source

All Articles