Javascript全局模块或全局变量 [英] Javascript global module or global variable

查看:82
本文介绍了Javascript全局模块或全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我无法提出更好的问题标题.

I couldn't come up with a better question title, sorry.

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

My question is, in he.js as per https://github.com/mathiasbynens/he/blob/master/he.js , they are using the following code:

/*! 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(...)的形式调用页面中的方法.

You will be able to call the methods in your page as he.encode(...).

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

My question is, how exactly does it set the variable he?

我的意思是,我可以看到

I mean, I can see the

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

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

But at the call of }(this));, what exactly is this?

推荐答案

让我们简化一下:

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

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

So, we have a function that takes an argument called root. This function is being immediately invoked (http://benalman.com/news/2010/11/immediately-invoked-function-expression/), and we are passing the value this to it.

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

In this context, this is your global object. If you are using a browser, your global object will be window.

因此,如果您确实在使用浏览器:

So, if you are indeed using a browser:

 root.he = he;

实际上与以下内容相同:

is actually the same as:

window.he = he;

并且请注意,我们不必一定要使用浏览器,这要归功于Node之类的平台,现在还有其他上下文,其中this全局对象不是window.这就是为什么另一个人没有明确指定window并进行此特定练习的原因.

And note, we don't necessarily need to be using a browser, thanks to platforms like Node there are now other contexts where the this global object is something other than window. That's why the other doesn't specify window explicitly and goes through this particular exercise.

这篇关于Javascript全局模块或全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆