0

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 ?

7
  • 1
    the downside is that it's a plain object and you don't have the encapsulation provided by a closure. Commented Aug 12, 2016 at 20:33
  • Could you please elaborate on that ? I understand what is happening in the below answer, but that has nothing to do with my module creation. The answer is just exeuting a function and some code. There is no module or enacapsulation being created. Are you saying in my object I can access MyClass.a and MyClass.b etc., but if I were to use an IIFE, would be able to control that ? If I had to rewrite this as an IIFE how would I do it ? thanks I am js newb Commented Aug 12, 2016 at 21:18
  • Of course there is encapsulation - you cannot reach x because it's inside the closure. The answer doesn't create a module but it's because the intention is to show what your solution would be lacking, not because it's showing "how to make a module". Given that you claim you know that already, it'd be redundant to go over it again. Commented Aug 12, 2016 at 21:20
  • When I claim to be able to make a module, I a referring to the MyClass code above. If I had no need to have private variables like x, would my way of making "module" be sufficient ? If not could you please show me how to with IIFE ? I am going to have take a long look at it to understand Commented Aug 12, 2016 at 21:36
  • I wrote an answer about that a couple of weeks back, it's verbose but I think it should answer your questions. Feel free to check the links in there for additional information on the subject - most notably closures (also shows up as related in this question) and the links I have on different takes on the module pattern. Commented Aug 12, 2016 at 21:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.