如何在define函数中获取全局范围?

时间:2013-06-05 09:57:38

标签: javascript scope requirejs global-variables requirejs-define

使用严格模式时是否可以获得全局范围,并确保可以在非窗口环境中运行。

请参阅以下示例:

define(['other', 'thing'], function() {
    // this === window in desktop environment
    // this === GLOBAL in node environment
});
define(['other', 'thing'], function() {
    "use strict";
    // this === undefined in desktop environment
    // this === GLOBAL in node environment
    // As of my understanding node has to be configured using `node --use_strict`
    // (http://stackoverflow.com/questions/9031888/any-way-to-force-strict-mode-in-node)
    // But that not the point.
});

有没有办法在window内获取全局变量(GLOBAL / define)。

5 个答案:

答案 0 :(得分:8)

var global = Function("return this")();

如果您无权访问Function,请尝试

var Function = function(){}.constructor,
    global = Function("return this")();

答案 1 :(得分:1)

这可能有所帮助,也可能无效,但我确实提出了一种使用以下代码覆盖requirejs模块上下文的方法......

require.s.contexts._.execCb = function(name, callback, args) {
    return callback.apply(/* your context here */, args);
};

再次,不确定这对use strict和所有人有帮助,但谁知道......:)

https://gist.github.com/jcreamer898/5685754

答案 2 :(得分:0)

到目前为止我所得到的是:

(function(root) { // Here root refers to global scope
    define('mything', ['other', 'thing'], function() {

    });
}(this);

但是我不能用r.js来缩小我的申请。

另一种可能是检查使用方法:

define(['other', 'thing'], function() {
    var root = typeof GLOBAL != 'undefined' ? GLOBAL : window;
});

另一种定义返回全局文件的全局文件的方法:

<强> global.js:

define(function() {
    return typeof GLOBAL != 'undefined' ? GLOBAL : window;
});

<强> mything.js

define(['global', 'other', 'thing'], function(root) {
    // root === window/GLOBAL
});

但是我不喜欢这种方式,因为如果引入了一些3.全局变量会破坏,或者如果浏览器环境中的用户定义了GLOBAL,那么将会返回。

我想看看是否有人提出了更聪明的方法。

答案 3 :(得分:0)

如果您将窗口引用存储在另一个可通用的对象上,例如Object.prototype或沿着这些行的某些内容,该怎么办?

答案 4 :(得分:0)

这是我通常做的(它适用于浏览器,node.js和RingoJS - 即使在严格模式下):

if (!global) var global = this;

define(['other', 'thing'], function() {
    // use global
});

define(['other', 'thing'], function() {
    "use strict";
    // use global
});

阅读以下StackOverflow线程以获取更多详细信息:Defining an implementation independent version of the global object in JavaScript

相关问题