Object Oriented Programming #26: Use an IIFE to Create a Module

Tell us what’s happening:

It isn’t mentioned why a return statement is necessary in this instance, but not in the previous mixin and prototype chain challenges. If anyone could explain, ty!

  **Your code so far**
let funModule = (() => {
  return {
    isCuteMixin: (obj) => {
      obj.isCute = () => {
        true;
      };
    },
    singMixin: (obj) => {
      obj.sing = () => {
        console.log(`Singing to an awesome tune`);
      };
    },
  };
})();
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36

Challenge: Use an IIFE to Create a Module

Link to the challenge:

1 Like

The task doesn’t say, that return statement is necessary, and the statement isn’t required.

When using a constructor or class (using the new keyword), Javascript follows a process:

  1. Create a new empty object ({}).
  2. Set the prototype of that object to the constructor.
  3. Execute the constructor function, using that empty object as the context (this).
  4. Unless the constructor stipulates an explicit return, the constructor returns that newly constructed object.

So with classes or constructors, we could manually do those steps ourselves. We could create our own object, wire it to a prototype chain, construct on that object, and explicitly return that.

But at that point, other than wiring it to the prototype chain, we’ve basically created a Factory Function or a Module.

Constructors and classes rely on inheritance, and the new keyword handles that for us. Modules and factories rely less on inheritance, as they create and compose the returned object themselves.

Thank you for the context!

1 Like

Thank you for the great question, and looking forward to seeing the wonderful things you do! :grin:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.