3

您可以在使用嚴格模式時獲得全局作用域,並確保您可以在非窗口環境中運行。如何在定義函數中獲取全局作用域?

參見這些例子:

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

有什麼辦法進去define全局變量(window/GLOBAL)。

+0

可能重複:http://stackoverflow.com/q/8280137/783743 –

回答

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

如果您沒有訪問Function,然後也儘量

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

如果我們使用CSP並且不允許不安全評估,這些將會被阻止。例如:'未捕獲的EvalError:拒絕評估字符串爲JavaScript,因爲'unsafe-eval'不是下列內容安全策略指令中允許的腳本源:「script-src https:'self'」。 – Serg

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那麼將返回該變量。

我想看看是否有人想出了一個更聰明的方法。

0

如果將窗口引用存儲在另一個可普遍訪問的對象上,例如Object.prototype或沿着這些行的東西,該怎麼辦?

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

相關問題