Ka Pr
Ka Pr

Reputation: 85

javascript module creation and initialization

My js does this:

var MyClass ={
        a: 1,
        b: 2,
        init: function(message){ console.log("calling c to say "+message);};
 };

 MyClass.init("hello");

//all above code is in js file

I keep seeing the IIFE pattern all over, but I am afraid I don't see what benefit it gets me compared to above. I have a module MyClass and ability to call methods on it. Is there a downside to using this pattern ?

Upvotes: 0

Views: 278

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

An IIFE is used to create a new function scope to avoid leaking variables into the global scope:

(function() {
    var x = 1;
    console.log(x); // 1
})();

console.log(x);     // undefined

This has basically nothing to do with calling a function stored in an object as in your example.

Upvotes: 1

Related Questions