简体   繁体   English

如何从 JS 文件中分配匿名 function

[英]How to assign an anonymous function from a JS file

hope everyone will be doing good.希望每个人都会做得很好。

I am working on a project, which uses fabric.js, and I have a JS file that looks like this:我正在开发一个使用fabric.js的项目,并且我有一个如下所示的JS文件:

(function(){
    this.foo = 'bar';
    this.bar = 'foo';
    ...........
    ...........
    ...........
    ...........
})();

Now, if I want to store the result of the above script to a global variable, how can I achieve this?现在,如果我想将上述脚本的结果存储到一个全局变量中,我该如何实现呢?
I want this:我要这个:

window.xyz = (function(){
    this.foo = 'bar';
    this.bar = 'foo';
    ...........
    ...........
    ...........
    ...........
})();

But, as I have said that this code is in a separate JS file, how can I achieve this?但是,正如我所说,这段代码在一个单独的 JS 文件中,我该如何实现呢?

You can't directly do what you've said you want to do unless you can change the other file so that it either puts the result in a global for you or exports its result, etc.你不能直接做你说你想做的事,除非你可以改变另一个文件,以便它把结果放在你的全局中或导出它的结果等。

The indirect way you can do it is by reading the file as a string, adding return at the beginning of the string, and converting it to code via new Function :间接方法是将文件作为字符串读取,在字符串的开头添加return ,然后通过new Function将其转换为代码:

window.xyz = new Function("return " + theFileContents)();

I do not recommend this unless you can absolutely trust the contents of the file (the same way you'd trust a file you loaded via import or require ).不建议这样做,除非您可以绝对信任文件的内容(就像您信任通过importrequire加载的文件一样)。 If you can trust it, this works, but it's a workaround.如果您可以信任它,这可行,但这是一种解决方法。

The real solution is to modify the other file.真正的解决方案是修改其他文件。


You've said this is in a browser.你说过这是在浏览器中。 That means you can use fetch to load the other file:这意味着您可以使用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...
});

That's trusting the content of that file as much as <script src="./the-other-file.js"></script> in your HTML would be.这与 HTML 中<script src="./the-other-file.js"></script>一样信任该文件的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM