问题
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:
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.
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!
回答1:
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:
- https://stackoverflow.com/a/7341755/96100
- How to get the global object in JavaScript?
来源:https://stackoverflow.com/questions/23834572/global-context-inside-umd-pattern