博主信息
博文 8
粉丝 1
评论 0
访问量 7558
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
ES6 模块知识入门
不露声色
原创
828人浏览过

关于模块

  • 2021-4-12

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <!-- 注意这里的type 必须带上,否则会报Uncaught SyntaxError: Cannot use import statement outside a module 的致命错误-->
    11. <script type="module">
    12. //这里如果是引用默认的模块不需要加上小夸号
    13. import hello , { userName , User } from "./module1.js";
    14. console.log(userName);
    15. console.log(hello("assd"));
    16. let a = new User("asdasdd",999);
    17. a.print();
    18. //控制台输出结果如下
    19. </script>
    20. </body>
    21. </html>

  1. //module1.js
  2. //关于模块知识
  3. let userName = "pandacode";
  4. function hello(name){
  5. return "hello" + name;
  6. }
  7. class User
  8. {
  9. //构造函数
  10. constructor(product,price){
  11. this.product = product;
  12. this.price = price;
  13. }
  14. //函数输出
  15. print(){
  16. console.log(this.product + this.price);
  17. }
  18. }
  19. //模块可以对变量函数类进行导出
  20. //但仅允许导出一个默认模块
  21. export { userName , User , hello as default}
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script type="module">
  11. //如果使用命名空间,我们可以先看下这个对象
  12. //此时默认模块的hello 被default代替
  13. import * as namespace from "./module1.js";
  14. console.log(namespace);
  15. // import hello , { userName , User } from "./module1.js";
  16. console.log(namespace.userName);
  17. console.log(namespace.default("assd"));
  18. let a = new namespace.User("asdasdd",999);
  19. a.print();
  20. </script>
  21. </body>
  22. </html>

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学