【问题标题】:Javascript global module or global variableJavascript 全局模块或全局变量
【发布时间】:2015-03-07 16:41:06
【问题描述】:

抱歉,我想不出更好的问题标题。

我的问题是,在 he.js 中,根据 https://github.com/mathiasbynens/he/blob/master/he.js ,他们正在使用以下代码:

/*! https://mths.be/he v0.5.0 by @mathias | MIT license */
;(function(root) {

    //...omitted

    var he = {
        'version': '0.5.0',
        'encode': encode,
        'decode': decode,
        'escape': escape,
        'unescape': decode
    };

    // Some AMD build optimizers, like r.js, check for specific condition patterns
    // like the following:
    if (
        typeof define == 'function' &&
        typeof define.amd == 'object' &&
        define.amd
    ) {
        define(function() {
            return he;
        });
    }   else if (freeExports && !freeExports.nodeType) {
        if (freeModule) { // in Node.js or RingoJS v0.8.0+
            freeModule.exports = he;
        } else { // in Narwhal or RingoJS v0.7.0-
            for (var key in he) {
                has(he, key) && (freeExports[key] = he[key]);
            }
        }
    } else { // in Rhino or a web browser
        root.he = he;
    }

}(this));

如果你把它导入到你的页面中

<script src="he.js"></script>

您可以将页面中的方法称为he.encode(...)

我的问题是,它究竟是如何设置变量he的?

我的意思是,我可以看到

    } else { // in Rhino or a web browser
        root.he = he;
    }
}(this));

但是在}(this)); 的调用下,this 到底是什么?

【问题讨论】:

  • this 将是window, - 执行函数时的this 实例,即window
  • @RaraituL 哦,我明白了!谢谢你。我以为可能是document 什么的,没想到window。再次感谢!
  • he.js 加载时,它定义了一个匿名函数(文件中顶级 {} 之间的所有内容)。然后它通过传递窗口对象调用该函数。它是通过执行'(this));'来完成的

标签: javascript module global


【解决方案1】:

让我们简化一下:

;(function(root) {
    ...
}(this));

所以,我们有一个函数,它接受一个名为root 的参数。立即调用此函数 (http://benalman.com/news/2010/11/immediately-invoked-function-expression/),我们将值 this 传递给它。

在这种情况下,this 是您的全局对象。如果您使用的是浏览器,您的全局对象将为window

所以,如果你确实在使用浏览器:

 root.he = he;

其实是一样的:

window.he = he;

请注意,我们不一定需要使用浏览器,多亏了像 Node 这样的平台,现在在其他上下文中,this 全局对象不是window。这就是为什么其他人没有明确指定window 并进行此特定练习的原因。

【讨论】:

  • 这太酷了!我之前使用过var globalVariable = (function(){...})();,但传递this 使其比仅使用全局常量更漂亮。
猜你喜欢
  • 2016-02-10
  • 1970-01-01
  • 2016-10-20
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多