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

and*_*lrc 3 javascript scope global-variables requirejs 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.
});
Run Code Online (Sandbox Code Playgroud)

有没有办法让内部的全局变量(window/ GLOBAL)define.

Esa*_*ija 8

var global = Function("return this")();
Run Code Online (Sandbox Code Playgroud)

如果您无权访问Function,那么也试试

var Function = function(){}.constructor,
    global = Function("return this")();
Run Code Online (Sandbox Code Playgroud)

  • 如果我们使用CSP并且不允许不安全评估,这些将被阻止.例如:`Uncaught EvalError:拒绝将字符串评估为JavaScript,因为'unsafe-eval'不是以下内容安全策略指令中允许的脚本源:"script-src https:'self'". (3认同)