JavaScript encapsulation

6

If you create a global JavaScript variable, it can be easily accessed from the console:

<script>
     var minhaVariavel = 0;
<script>

But if I create it like this:

<script>
     $(document).ready(function (){ 
          var minhaVariavel = 0; 
     });
<sctip>
Is it possible to access it at all, or is it really safe? Home I need a way of not letting my variable be accessible to the console.

    
asked by Jedaias Rodrigues 21.10.2015 в 15:59
source

3 answers

6

Insurance is a relative term.

If you want to know if it's going to pop up anytime and unintentionally access it, you're certainly safe.

If you want to know if there is no forced medium (see bfavaretto's answer) and it is not normal to access it, I can not guarantee it anymore. But why would I do that?

If you are thinking that the value of the variable will be obscured, protected and nobody will be able to see it, forget it. Sensitive information should not be in a JS code, nor temporarily.

    
answered by 21.10.2015 / 16:18
source
3

As the bigown has said, it depends on your security concept. Declaring the variable within a function prevents other scripts from reading or changing their value. However, it does not prevent a person with a debugging tool from being able to do these operations.

Depending also on what you do in the rest of the code, the variable may end up being accessible, because of you. Every function declared within your document.ready will have access to the variable. If one of these functions changes the value, and that function for some reason ends up exposed in the global scope, an external code could invoke it and indirectly change the value of the variable.

    
answered by 22.10.2015 в 15:06
0

The encapsulation serves to help the variables not conflict during the execution of your application and also does not pollute the overall scope of the browser. However there is a code design pattern that assists with the namespace and encapsulation and obfuscation of your code. If you want to see the response it receives, just debug the code that will have the answers of what it receives.

    
answered by 15.07.2016 в 16:02