Scope between variables - Javascript

2

Hello

I'm studying Javascript and I'm having a question. I come from a world called Java and there exists the modifiers of access private, protected, public and even variable without declaration of modifier; and with that I'm a little lost in javascript.

Is it possible to display the file1.js variable through a function, for example in file2.js? Usually in java we leave the variable public or we use getters and setters for such action.

I had this doubt because in an online course I came in the scope part and only addresses the scope in relation to the file itself, but the guy who teaches recommends being careful with scopes because a variable can be accessible anywhere else in the project, but does not elaborate.

I wanted to know how this question works in javascript, as my interest is to learn how to work with JS in the backend with NodeJs.

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

Thank you in advance!

    
asked by anonymous 09.02.2017 / 21:54

2 answers

3

I think this explains. Declare the variables outside the return and the inner functions you want to hide, declare as per the 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:

    
09.02.2017 / 22:50
3

What you're talking about ("You can see the variable of file1.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 a basic functionality of Node.JS modules). This utility will create a log for each file (module).

If ECMAScript 4 was present in JavaScript there would be access modifiers, and classes would be much more beautiful, even more than ECMAScript 6 (in my opinion). For now it is possible to hide properties over 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).

    
10.02.2017 / 14:57