Encapsulation in Javascript

Asked

Viewed 941 times

8

If I 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 somehow access it or is it really safe?

I need a way to not let my variable be accessible to the console.

  • 1
  • 1

    Remember that code encapsulation is something that helps to write correct code. Encapsulation serves no purpose in security issues because the user can replace his code with another if he wants (after all, he is the owner of the computer)

  • 1

    related to the encapsulation concept: http://answall.com/a/85755/13561

3 answers

7


Insurance is a relative term. If you want to know if she will pop up at any time elsewhere and access it unintentionally, you are certainly safe.

If you want to know if there is no forced means (see bfavaretto response) and out of the normal to access it, I can no longer guarantee. But then why would I do this?

If you think the value of the variable will be obscured or protected and no one can see it, forget it. Sensitive information should not be in a JS code, nor temporarily.

  • 1

    Ironic, until yesterday I’m even thinking a ask a question on this subject, and regarding the security of the encapsulated code. Good is no longer necessary.

3

As Maniero said, it depends on your security concept. Declaring the variable within a function prevents others from scripts read or change its value. However, it does not prevent a person, armed with a tool of debugging, can do these operations.

Depending also on what you do in the rest of the code, the variable may end up accessible because of you. Every function declared within your document.ready you will have access to the variable. If one of these functions changes the value, and this 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.

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.