1

Here is an example of a pseudo class in an IIFE

// cow.js
(function(exports) {
  "use strict";

  function Cow(name) {
    this.name = name || "Anon cow";
  }
  exports.Cow = Cow;

  Cow.prototype = {
    greets: function(target) {
      if (!target)
        throw new Error("missing target");
      return this.name + " greets " + target;
    }
  };
})(this);

What is the benefit of that over the following:

  "use strict";

  function Cow(name) {
    this.name = name || "Anon cow";
  }
  exports.Cow = Cow;

  Cow.prototype = {
    greets: function(target) {
      if (!target)
        throw new Error("missing target");
      return this.name + " greets " + target;
    }
  };

Don't both of these end up adding the Cow 'constructor' function to the global scope?

The cow.js file is being included via the HTML document in a script tag. That means that the value of this is window. Isn't that the same global scope that both examples will use to add the function to?

Could someone provide an example of using this in a module or different scope?

This is not a duplicate, as the IFFE in the following related question does not take a parameter - What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

The code was copied from here: https://nicolas.perriault.net/code/2013/testing-frontend-javascript-code-using-mocha-chai-and-sinon/

Community
  • 1
  • 1
Daryn
  • 3,394
  • 5
  • 30
  • 41
  • 1
    @Tushar could you please explain this in more detail? – Daryn Nov 10 '15 at 11:35
  • In the second example Cow becomes a global method (supposed it is defines at window scope, so it becomes window.Cow), while it's not in the first example. – Stranded Kid Nov 10 '15 at 11:38
  • I don't think this a duplicate. It is asking about the use of 'this' which the other question does not address explicitly. – Daryn Nov 10 '15 at 14:09

1 Answers1

0

The difference is the scope - in the 1st case everything is defined in an anonymous function scope, in 2nd case in global scope. The benefit of IIFE is module encapsulation, you can define a function/class with the same name in each module without affecting another one.

Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29
  • I have added more detail to the question, about the fact that this script is being included via an HTML page. Doesn't this mean that both version are adding `Cow` the the window scope? – Daryn Nov 10 '15 at 15:16