3

I am writing an agnostic logging mechanism that works inside the browser and in nodejs (e.g. console.debug is missing in nodejs).

// UMD with no dependencies
(function(global, factory) {
    if (typeof module === 'object') {        
        module.exports = factory();

        // GLOBAL IS NOT WHAT I WOULD EXPECT, YOU?
        global.console = factory();

    } else if (typeof define === 'function' && define.amd) {
        define(factory);
    } else {
        global.console = factory();
    }
})(this, function() {
    function logger() {};
    return logger;
});

I stumbled upon 2 differences I cannot explain:

  1. As expected, for the browser case the variable 'global' has the value of window. However, with Nodejs 'global' is just a simple object and not the global variable of Nodejs. Is this intended? One could execute the module using '.call' to preserve the corresponding context for the browser and Nodejs. As this is a common accepted UMD pattern, I was doubting if it is a bad idea to modify the global variable in Nodejs, which takes me to next question.

  2. Inside the browser it is possible to overwrite the global console function by passing over my custom object to the console property. One could have back the old behaviour by restoring the reference to the original object. This is not possible in Nodejs, it fails when I am trying to pass my own logger object to global.console. Strange enough, that I did not find any useful documentation in the web...

Hope to get some clarifications!

crishushu
  • 435
  • 2
  • 4
  • 14

1 Answers1

2

UPDATE

Apparently the following may not work in all situations in Chrome. See the comments to this answer.

Original answer

I'm using the following instead of this in my code to get the global object. It seems watertight in ECMAScript 3 and 5 environments:

(function(f) { return f("return this")(); })(Function)

This is a little indirect in an effort to appease linters, such as JSLint, that don't like use of eval and the Function constructor. If you don't care about such things (yay for you), you can use the following simpler code instead:

Function("return this")()

Background:

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 1
    In the post you [linked to](http://stackoverflow.com/q/3277182/508355), somebody noted in the comments that it might not work in all environments, after all. _In Chrome I am getting: EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'unsafe-inline'"_ ([this answer](http://stackoverflow.com/a/3277192/508355), comment by @Pat) – hashchange Aug 04 '16 at 14:48