Private and public Javascript features

can someone explain what is the difference between these two functions?

(function(Engine, $, undefined) { //hidden from scope //public function below Engine.Init = function() { console.log("IM PUBLIC"); } //anonymous functions below function Login() { console.log("IM PRIVATE"); } })( window.Engine = window.Engine || {}, jQuery ); 

In particular, I would like to know why Engine.Init() is available in the Console , but the Login no.

+4
source share
4 answers

Init is a property of the Engine object that references a function.
You can access it, like any other property.

Login - a local variable in the anonymous, "immediately called function expression" (IIFE); like other local variables, its name is displayed only inside the declaration function

+7
source

The engine is global because of the parameters:

 (window.Engine = window.Engine || {}, jQuery) 

and available in the global namespace if you have done this:

 Engine.Login = function(){} 

It will be available worldwide.

The Login function is available only within the scope of the anonymous self-emitting function.

+2
source

In fact, there is no difference between the functions themselves. The only difference is that the first function is assigned to the property of the object ( Engine.init ) defined in the global area ( window.Engine ), while the second function is defined locally inside the function expression (IIFE) is called immediately .

Here is an equivalent but simpler example:

 function foo() { // 1 window.globalFunc = function() { // global/public } // 2 function localFunc() { // local/private } } foo(); 

Since the first function is explicitly assigned to a global variable, it can be accessed outside of foo after foo executed. localFunc not exported and therefore locally in foo , i.e. it cannot be accessed and does not exist outside of foo .

+2
source

This thing

 function(Engine, $, undefined) { ... } 

actually a closure. Thus, everything is defined inside this function, available only in this area. When you do

 Engine.Init = ... 

You create a property attached to an Engine object. In your case, the engine is a global object, which means that you have access to it through the console.

0
source

Source: https://habr.com/ru/post/1497270/


All Articles