[英]How to assign an outer scoped variable from within an anonymous function being used as a param in JS?
[英]How to assign an anonymous function from a JS file
希望每個人都會做得很好。
我正在開發一個使用fabric.js的項目,並且我有一個如下所示的JS文件:
(function(){
this.foo = 'bar';
this.bar = 'foo';
...........
...........
...........
...........
})();
現在,如果我想將上述腳本的結果存儲到一個全局變量中,我該如何實現呢?
我要這個:
window.xyz = (function(){
this.foo = 'bar';
this.bar = 'foo';
...........
...........
...........
...........
})();
但是,正如我所說,這段代碼在一個單獨的 JS 文件中,我該如何實現呢?
你不能直接做你說你想做的事,除非你可以改變另一個文件,以便它把結果放在你的全局中或導出它的結果等。
間接方法是將文件作為字符串讀取,在字符串的開頭添加return
,然后通過new Function
將其轉換為代碼:
window.xyz = new Function("return " + theFileContents)();
我不建議這樣做,除非您可以絕對信任文件的內容(就像您信任通過import
或require
加載的文件一樣)。 如果您可以信任它,這可行,但這是一種解決方法。
真正的解決方案是修改其他文件。
你說過這是在瀏覽器中。 這意味着您可以使用fetch
加載另一個文件:
fetch("./the-other-file.js")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.text();
})
.then(code => {
window.xyz = new Function("return " + code)();
})
.catch(error => {
// ...handle/report error...
});
這與 HTML 中<script src="./the-other-file.js"></script>
一樣信任該文件的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.