Reputation: 10713
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.
Upvotes: 4
Views: 334
Reputation: 887469
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
Upvotes: 7
Reputation: 816482
There is not really a difference between the functions themselves. The only difference is that the first function is assigned to a property of an object (Engine.init
) defined in global scope (window.Engine
), whereas the second function is defined locally inside the immediately invoked function expression (IIFE).
Here is a equivalent, but simpler example:
function foo() {
// 1
window.globalFunc = function() {
// global/public
}
// 2
function localFunc() {
// local/private
}
}
foo();
Because the first function is explicitly assigned to a global variable, it can be accessed outside of foo
, after foo
was executed. localFunc
is not exported and hence local to foo
, i.e. it cannot be accessed and doesn't exist outside of foo
.
Upvotes: 2
Reputation: 13529
This thing
function(Engine, $, undefined) {
...
}
is actually a closure. So everything define inside that function is available only in that scope. When you do
Engine.Init = ...
You create a property which is attached to Engine object. In your case Engine is a global object, which means that you have an access to it via the console.
Upvotes: 0
Reputation: 4332
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.
Upvotes: 2