Jwan622
Jwan622

Reputation: 11659

What's the difference between this self-executing anonymous function and this normal function call?

What's the difference between this:

(function() {
    var Person = {
        sayHello: function() {
            alert('Hello World');
        }
    }

    Person.sayHello();
})();

And this:

var Person = {
    sayHello: function() {
        alert('Hello World');
    }
}

Person.sayHello();

Besides the latter creating a public function and the former being a way to create a kind of private function (you cannot reference Person outside of the parenthesis... what's the difference?

Upvotes: 1

Views: 74

Answers (4)

Angel Politis
Angel Politis

Reputation: 11313

The first one is a Self-Executing Anonymous Function, which means that nothing defined in there is accessible outside of it and when it executes, everything inside it is "lost".

To be able to call the sayHello() method outside that function you have to expose the object Person to the global ‘window’ object:

//Assign 'Person' to the global variable 'Person'
window.Person = Person;

The second one is variable containing an object and since that variable is declared in the global scope, it is accessible from everywhere and new methods and properties as well as instances of the object can be created.

Upvotes: 1

Alexey
Alexey

Reputation: 999

the 1st version creates 'isolated namespace', so if you have the Person variable somewhere in your code, then it won't be overwritten

The 2nd version creates Person in global scope, so in can lead to conflicts with another parts of your code

more info

Upvotes: 2

Quentin
Quentin

Reputation: 944430

The first one doesn't leave a variable called Person floating around the current scope (because there are no references to it left when the IIFE finishes executing), nor does it overwrite any other variables called Person in that scope.

(The second one is missing a } but I assume that is a typo in the question).

Upvotes: 8

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

The first one has the Person variable private. Once executed, it discards everything inside the SE Function.

Upvotes: 2

Related Questions