Search code examples
javascriptiife

iife returned function not working correctly


I'm trying to create a module, and I'm trying to use the correct design. I saw this library, and they had a iife returning the function that's a module. I tried doing that like this:

(function() {
  function MyModule() {
    var something = 'something';
    this.log = log();
  }

  MyModule.prototype.alert = function() {
    alert(this.something);
  };

  function log() {
    console.log('hello');
  }

  return MyModule;
})();

var module1 = new MyModule();

But I get the following error:

Uncaught ReferenceError: MyModule is not defined

Here's the relevant copied code:

What am i doing wrong, and how can I fix it?


Solution

  • MyModule is staying inside the IIFE clousure so it wont be visible from code outside. Assign the result of the IIFE to a MyModule variable

    Also, you probably meant to assign the log function to the MyModule being constructed, and not its result (undefined)

    And finally, the fact that you declare a variable called something in the constructor does not assign it as a property of the object being constructed. If you wanted something to be private, you have to declare the alert method inside the clousure of the constructor:

    var MyModule = (function() {
      function MyModule() {
        var something = 'something';
        this.log = log;
        // this.log = log();
    
        this.alert = function() {
            alert(something);
        };
      }
    
      //MyModule.prototype.alert = function() {
      //    alert(this.something);
      //};
    
      function log() {
        console.log('hello');
      }
    
      return MyModule;
    })();
    
    var module1 = new MyModule();
    
    module1.alert(); // Alerts 'something'
    module1.log(); // Logs 'hello'
    

    To really understand JavaScript, forget about classes, learn about prototypes and functions in general, specially clousures.

    Watch this brilliant conference by Douglas Crockford to get it right.