如何在定义函数内获取全局作用域?

3

在使用严格模式和确保能够在非 window 环境下运行的同时,你能否获取全局作用域?

看这些例子:

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`
    // (https://dev59.com/mGox5IYBdhLWcg3wsGWC)
    // But that not the point.
});

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

可能是重复的问题:https://dev59.com/f13Va4cB1Zd3GeqPCqgG - Aadit M Shah
5个回答

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

如果您无法访问Function,则也可以尝试以下方法。
var Function = function(){}.constructor,
    global = Function("return this")();

4
如果我们使用 CSP 并且不允许 unsafe-eval,那么这些内容将被阻止。例如:Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src https: 'self'" - Serg

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


0

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

if (!global) var global = this;

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

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

阅读以下StackOverflow帖子以获取更多详细信息:在JavaScript中定义一个与实现无关的全局对象版本


0
如果您将窗口引用存储在另一个普遍可访问的对象上,例如Object.prototype或类似的东西,会怎样呢?

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

但是我不喜欢这种方法,因为如果引入某些全局变量,则会导致错误,或者如果用户在浏览器环境中定义了GLOBAL,则会返回该变量。

我想知道是否有更聪明的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接