Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private vs Public Javascript Functions

Tags:

javascript

can someone please explain what the difference is 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 );

Specifically, I'd like to know why Engine.Init() is available in the Console but Login isn't.

like image 934
Barrie Reader Avatar asked Dec 20 '22 01:12

Barrie Reader


2 Answers

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

Login is a local variable within the anonymous, "immediately invoked function expression" (IIFE); like other local variables, its name is only visible within the declaring function

like image 92
SLaks Avatar answered Dec 22 '22 15:12

SLaks


Engine is global because of the parameters:

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

and available in the global namespace, if you did:

Engine.Login = function(){}

That would be available globally.

The function Login is only available inside the scope of the anonymous self executing function.

like image 24
Michael Benin Avatar answered Dec 22 '22 14:12

Michael Benin