【问题标题】:How to access and assign function from a window object in JS?如何从 JS 中的窗口对象访问和分配功能?
【发布时间】:2021-05-24 08:05:16
【问题描述】:

我试图将一个函数分配给像 main.js

中这样的窗口对象
var _init_ = function(id = "") {
    //do something
}
window._init_ = _init_;

现在我尝试通过附加如下脚本从 index.html 调用该函数:

<script type="module" src="./main.js"></script>
<script type = "text/javascript">
    _init_();
</script>

但是当我刷新浏览器时它给了我Uncaught ReferenceError: _init_ is not defined 虽然当我尝试通过浏览器控制台中的window._init_ 访问它时它正在返回该函数。

注意:我已将脚本作为module 导入,因为我已将 js 代码分解为不同的 js 文件并将其作为一个文件使用

问题/疑问:如何分配和访问窗口对象中存在的函数,保持 id 为可选,这意味着如果 id 未在函数调用中传递,它将是一个空字符串,或者如果传递了 id,它将接受传递字符串。

【问题讨论】:

    标签: javascript function object window


    【解决方案1】:

    模块异步运行。 _init_ 未在您的内联脚本运行时定义。

    虽然有一些方法可以让内联脚本在模块加载后从模块中获取信息,但它不会那么优雅。到目前为止,最好的方法是:

    现在我尝试从 index.html 调用函数

    成为入口点本身:

    <script type="module">
    import { init } from './main.js';
    init(); // pass an ID here if you want
    </script>
    
    // main.js
    export const init = function(id = '') {
      // do something
    }
    

    【讨论】:

      【解决方案2】:

      一种通过动态加载实现此目的的方法。

      function loadScript() {
        const script = document.createElement('script');
        script.src = "./main.js";
        document.body.appendChild(script);
      
        return new Promise((res, rej) => {
           script.onload = function() {
            res();
         }
       });
      }
      
      
      loadScript()
       .then(() => {
        console.log('loaded, now you can use what ever you need from main.js');
      });
      

      还有一种是使用onLoad事件:

      <script onload="callInit();" type="module" src="./main.js"></script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        • 1970-01-01
        • 2012-07-03
        相关资源
        最近更新 更多