找到你要的答案

Q:UMD javascript module which also works in strict mode

Q:UMD的JavaScript模块,在严格的工作方式也

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 {};
}));

我很难重写这个工作在'严格'模式。因为这是不明确的定义我越来越jshint错误编译。我想我的大脑是不是思维抽象地找到创造性的解决方案。任何帮助将不胜感激。从通用模块定义GitHub的回购代码: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 {};
}));
answer1: 回答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.

看看你的代码,我看到根实际上只在你使用浏览器的情况下使用,它简化了事情。

这意味着我们可以用以下表达式替换:

typeof window !== "undefined" ? window : undefined

这是有效的严格模式(我试过在节点,则返回未定义,没有错误),和jshint.com允许它。

如果在其他情况下也需要全局对象,则可以将三元表达式链接起来。

node.js  requirejs  umd