UMD javascript module which also works in strict mode
Asked Answered
T

1

1

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 {};
}));
Torpedo answered 14/8, 2015 at 14:34 Comment(2)
well... what does this refer to? It depends on environment right? you could just not pass that in at all, and instead refer to window in the else statement.Felisha
@KevinB Correct, this refers to the current environment. So using window will allow the correct functionality in some environments but will not allow interoperability between environments, which is my goal. I've updated my question with a link to the Universal Module Definition Github projectTorpedo
S
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.

Standin answered 14/8, 2015 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.