javascript ES6模块:即使附加到Windows.prototype也不能在html文件中工作,为什么?

9o685dep  于 2022-12-10  发布在  Java
关注(0)|答案(1)|浏览(136)

将函数定义为ES6模块,在type=module内的index.html中导入的外部JS文件中,由于import/export只能在模块内使用,然后将其设置在全局Window.prototype上,以便其可访问第二个script标记的代码范围,但其不工作。

索引.html

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <p>Simple html document.</p>

        <script type="module">
            import { showPlayerName } from './test.js'
            Window.prototype.showPlayerName = showPlayerName;
        </script>

        <script type="text/javascript">         
            showPlayerName();
        </script>
    </body>
    </html>

测试.js

export function showPlayerName(){
    return 'Leo Messi'; 
}

Error: index.html: Uncaught ReferenceError: showPlayerName is not defined
如果函数在<script type="module"></script>内部调用,而<script type="module"></script>甚至不运行,为什么
有人能让我知道为什么调用内部type=modulewindow.showPlayerName在非type="module"不会工作。
谢谢

xytpbqjk

xytpbqjk1#

当引擎在HTML中遇到模块脚本得<script>标记时,模块脚本不会立即运行:

<p>Simple html document.</p>

<script type="module">
  console.log('module running');
  window.showPlayerName = () => console.log('foo');
</script>

<script type="text/javascript">
  showPlayerName();
</script>

因此,当您尝试从非模块脚本调用showPlayerName时,它并没有被定义。
虽然有一些方法可以通过等待加载您感兴趣的模块脚本来解决这个问题,但更好的方法是,如果您有任何模块脚本,将 * 所有内容 * 放入模块中,这样就不会有问题了。

<script type="module">
  import { showPlayerName } from './test.js'
  showPlayerName();
</script>

这也有不需要创建任何全局变量的优点。

相关问题