2

I see this IIFE "template" a lot in Javasript libraries.

(function(window, document) {
  // code
}(typeof window !== "undefined" ? window : this, document));

And wanted to ask: In what case the window object is undefined? And in that case, what this is referencing to?

derive
  • 33
  • 1
  • 6

2 Answers2

1

The window could be undefined when the script is run on the server-side, for example, when using Node.js.

An example is shown here: https://github.com/tbranyen/use-amd/issues/4

Shotgun Ninja
  • 2,420
  • 3
  • 24
  • 32
0

Looking at your question you must be talking of the case when you run your javascript code on the server, that is node.js or any other fork of it.

In this case the neither the window object or the document object are defined because none of those exist on node so your code will throw a Reference Error. Removing the reference to the document object and testing the this variable

(function(window) {
    console.log(window);
    console.log(typeof window);
    console.log(Object.prototype.toString(window));
}(typeof window !== "undefined" ? window : this));

The output will be

{}
object
[object Object]

That is an empty object wich is a reference to the module.exports object. This is easy to test.

module.exports.test = function () {
    console.log('a');
};

(function(window) {
    window.test();
}(typeof window !== "undefined" ? window : this));

Will output a in the console. Check this SO question to learn more about the value of the this object in node.js.

Community
  • 1
  • 1
devconcept
  • 3,370
  • 1
  • 22
  • 38
  • Thanks, that makes sense. But one more question. Why isn't the same done for the **document** parameter as it is not defined as well? – derive May 20 '15 at 18:08
  • Remember that the reason of the window variable be pointing at the `this` variable is the code you write. By default neither window or document will be defined and that is beacuse in node.js there is no DOM tree unless you are using a package that implement's it like jsdom https://www.npmjs.com/package/jsdom. – devconcept May 20 '15 at 18:19