How do I set up a variable to point to the global object - regardless of the execution context?

Can someone explain to me what this means?

!function (global, moduleDefinition) {
  'use strict';

  var dependencies = [];

  if (typeof define === 'function' && define.amd) {
    define(dependencies, moduleDefinition);
  } else if (typeof exports === 'object') {
    module.exports = moduleDefinition.apply(null, dependencies);
  } else {
    global.Utilities = moduleDefinition.apply(null, dependencies);
  }

}(this, function () {
  'use strict';

  var Utilities = {};

  return Utilities;

});

      

This was handed over to me as our new module.

Joe

+3


source to share


2 answers


  • ! exclamation mark (or any other lie (+) character turns the code into an expression - you can call it immediately

Example

(function() {}());
!function() {}();

      

Invalid version

You cannot declare a function declaration!

function() {}() // wrong, don’t try to run this

      



Example

You can pass arguments to the called function

(function(foo) {
    console.log(foo, foo === 3); //3, true foo is equal to passed value
}(3));

      

You can pass a global object - in the browser environment it points to the window object , in Node it points to the global object . Since we want to write one version of the code without opening it up to detect the environment, it is easier to use a global variable that can hold a pointer to a global object. Compare window.setTimeout

(for browser) vs this.setTimeout

(for Node) vs global.setTimeout

(for both)

(function(global) {
    global.setTimeout(function() {
        console.log('I’m running independent to browser or server environment');
    }, 1000);
}(this));

      

Are you missing something for the moduleDefinition where is the rest?

+3


source


This means that the code following this statement must be executed in strict mode. This can be used to ensure that there are no errors in the code following this.



More information on strict mode: http://www.w3schools.com/js/js_strict.asp

-2


source







All Articles