javascriptstrictjavascript-namespaces

Why does "use strict" break function assignment inside namespace to global scope?


I have library code does a simple function assignment. This function is accessed from the global scope.

When I add "use strict" at the beginning of the file, I get an error TypeError: a is undefined, on assignment to a.b.

"use strict"; /* Remove this and 'a' is defined */
(function() {
  var a = this;
  a.b = function() {
    document.getElementById('test').innerHTML = 'abc';
  };
})();
b();
<div id="test"></div>

Why do I get this error considering that var a is declared on the previous line?


Solution

  • Global Leakage

    There are a number of situations that could cause this to be bound to the global object. For example, if you forget to provide the new prefix when calling a constructor function, the constructor's this will be bound unexpectedly to the global object, so instead of initializing a new object, it will instead be silently tampering with global variables. In these situations, strict mode will instead bind this to undefined, which will cause the constructor to throw an exception instead, allowing the error to be detected much sooner.

    so you do not have a as this, but your a is undefined, so you cannot make b to undefined