Scope between variables - Javascript

Asked

Viewed 586 times

2

Hello!

I’m studying Javascript and I have a question. I come from a world called Java and there are private access modifiers, protected, public and even variable without modifier declaration; and with that I am a little lost in javascript.

It is possible to view the arquivo1.js through a Function, for example, in the arquivo2.js? Normally in java we leave the publish variable or we use getters and setters for such action.

I had this doubt because in an online course I arrived at the scope part and only addresses the scope in relation to the file itself, but the boy who teaches recommends to be careful with scopes because a variable can be accessible anywhere else in the project, but does not expose more details.

I wanted to know how this issue works in javascript, because my interest is to learn how to work with JS in the backend with Nodejs.

Any material you recommend that I read? Or a lecture or video lesson that talks about?

Thanks in advance!

2 answers

3

That’s what you’re talking about ("You can view the file variable 1.js through a Function") could be possible in different ways, but the browser API does not directly enable it. It would be better to merge your files using webpack, for example (which adds basic functionality of Node.JS modules). This utility will create a factory for each file (module).

If the Ecmascript 4 was present in Javascript there would be access modifiers, and the classes would be much more beautiful, even more than Ecmascript 6 (in my opinion). For now it is possible to hide properties about an instance of a class (or similiar...) in a collection of weak references, or imitate @Maurivan’s solution (which will probably work in any browser).

  • 1

    It’s something very strange for me, but I’m getting used to the few rsrs Grateful my comrade!

3


I guess that explains it. Declare the variables outside of Return and the internal functions you want to hide, declare as code below:

var Main = function () {
    var fn = function () { // private
    }

    function fn2 () { // public
    }

    // private attr
    var options = {
        opt1: 'option1',
        opt2: 'option2'
    }

    return {
        options: { // public
         opt1: 'public option 1',
         opt2: 'public option 2'
        },
        init: function () {
         console.log ('Main function loaded...');
        }
    }
}();

See another example below:

Encapsulamento js

  • 1

    This helps me a lot. It’s still hard to get into the head 100%, but I’ll adapt. Thank you my dear! Vlw himself, helped a lot with the examples!

Browser other questions tagged

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