DONG
DONG

Reputation: 69

key word THIS in javascript as global namespace

I m reading code sample from here

You will find that it's IIFE in javascript. After reading some documentations, I understand well now what it is and how it works in a simple way.

But in the end of this script, it passes "this['routingConfig']"

(function(exports){

    // Other codes
    exports.userRoles = buildRoles(config.roles);
    // Other codes and definition of buildRoles

})(typeof exports === 'undefined' ? this['routingConfig'] = {} : exports);

Then it seems that we could in other script files invoke it directly like this:

var access = routingConfig.userRoles;

So what's the exact usage of

(typeof exports === 'undefined' ? this['routingConfig'] = {} : exports);

It seems that 'this' key word works as a global namespace, add 'routingConfig' as a key-value pair.

Upvotes: 0

Views: 46

Answers (1)

jfriend00
jfriend00

Reputation: 707916

This line of code:

(typeof exports === 'undefined' ? this['routingConfig'] = {} : exports);

Is ultimately going to decide what to pass as the first argument to the IIFE.

  1. If exports is defined in the current scope, then it will pass exports.
  2. If exports is not defined, then it will initialize this['routingConfig'] to an empty object and pass that empty object as the first argument.

If routingConfig.userRoles is accessible elsewhere in the code, then that's because this['routingConfig'] is setting a property on some object (whatever this points to in this code) and that object is apparently accessible elsewhere in your code.

It is possible that this points to the global object, but we'd have to see the entire context of the code to know for sure. If it does point to the global object, that could explain why it is accessible from other places in your code.


Personally, I never write code that assumes this is the global object. If I want to refer to the global object, I refer to it directly. Then anyone glancing at your code will know exactly what the code intends without wondering what this is set to.

My uses of this are almost exclusively either the host object in a method invocation or something specifically set via documentation when a callback function is called such as .addEventListener() for DOM events. This makes it much clearer from the local code context what this is set to.

Upvotes: 4

Related Questions