问题
I'm having trouble rewriting this to work in 'strict' mode. Since 'this' is not defined explicitly I'm getting jshint errors on compile. I'm thinking my brain is just not thinking abstractly enough to find a creative solution. Any help would be appreciated. Code adapted from the Universal Module Definition Github repo: https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD Module
define([], factory);
} else if (typeof module === 'object' && module.exports) {
// Node Module
module.exports = factory();
} else {
// Browser Global
root.returnExports = factory();
}
}(this, function () {
return {};
}));
回答1:
Looking at your code, I see that root
is only actually used in the case that you are in a browser, which simplifies things.
That means that we can replace this
with the following expression:
typeof window !== "undefined" ? window : undefined
This is valid in strict mode (I tried it in Node, it returns undefined
, no errors), and JSHint.com allowed it.
If you need the global object in other cases as well, you can chain the ternary expressions.
来源:https://stackoverflow.com/questions/32012589/umd-javascript-module-which-also-works-in-strict-mode