【无标题】

ES6

1.模块化

1.1什么是模块化

  • 模块化是指将一个大的程序文件,拆分成许多小的文件,然后将小文件组合起来。
  • 模块化的优势有以下几点:
    • 防止命名冲突
    • 代码复用
    • 高维护性
      没有模块化
var flag = false;
var flag = true;
<!-- js先后顺序回影响后边的逻辑 -->
<script src="./bar.js"></script>
<script src="./foo.js"></script>
<script>
    if (flag) {
        console.log('张三');
    }
</script>

闭包

var bar = (function(){
    return {
        flag:false,
    };
})();
var foo = (function () {
    return {
        flag: true,
    };
})();
<!-- 闭包解决模块化 -->
<script src="./foo.js"></script>
<script src="./bar.js"></script>
<script>
    if (foo.flag) {
        console.log('你好');
    }
</script>

2. ES6 模块化

  • 模块功能主要由两个关键字构成:export 和 import
  • export 命令用于规定模块的对外接口
  • import 命令用于输入其他模块提供的功能

18. export

export 有两种导出模式,export 和 export default(一个模块中只能有一个 default)

导出变量

export 后边可以是一个变量声明表达式或者是一个{}里边包含变量名,但是不能直接输出一个变量, export default 后边可以直接跟一个常量或者变量,但是不能跟声明表达式

export var a = 1 //正确

const age = 100
export { age } //正确

export age //错误

export default age //正确

export default 50 //正确

export default var name='abc ' //错误

导出函数

export 和 export 都可以直接导出函数声明语句,但是 export 后边不能跟匿名函数,如果直接导出函数名 export 需要用{}包裹

//正确
 export default function test () {
  console.log('test function')
}
   //正确
 export  function test2 () {
  console.log('test function')
}
//错误
 export  function  () {
  console.log('test function')
}
 //正确
 export default function  () {
  console.log('test function')
}

function test3(){
 console.log('test3 function')
}

//正确
expor {test3}
//正确
export default test3
错误
export  test3

使用 as 别名导出
let a = 100;

export { a as age };

19. import

  • 对于使用 export default 导出的,倒入时不需要使用{},且名字可以任意定义

  • 对于使用 export 导出的,必须使用{}倒入,且名字必须一致

  • 可以使用通配符* 方式全部导入 (import * as obj from ‘…/a.js’)

    //对于export default 导出的
    
    import myFn from './a.js';
    
    //对于使用export 导出的
    
    import { test1, test2 } from './a.js';
    
    使用 as 别名导入
    let a = 100;
    
    export { a as age };
    

20. 按需加载

采用回调函数的方式,所有的引入直接在回调中

document.onclick = function () {
  import('./a.js').then(data => {
    console.log(data);
  });
};

17. async 和 await

  • async 和 await 两种语法结合可以让异步代码像同步代码一样
  • async 函数的返回值为 promise 对象
  • promise 对象的结果由 async 函数执行的返回值决定
  • await 必须写在 async 函数中
  • await 右侧的表达式一般为 promise 对象
  • await 返回的是 promise 成功的值
  • await 的 promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理\
async的作用
<script>
    // 被async修饰的函数的返回值是一个Promise对象
    // 异步函数
    async function sum(a, b) {
      return a + b;
    }

    sum(10, 20).then(res => {
      console.log(res);
    });
  </script>

// function ajax({
//   url = '',
//   method = 'GET',
//   data = {},
//   header = { 'Content-Type': 'application/json' },
// } = {}) {
//   const xhr = XMLHttpRequest
//     ? new XMLHttpRequest()
//     : new ActiveXObject('microsoft.XMLHTTP');

//   xhr.onreadystatechange = () => {
//     const { readyState, status, responseText } = xhr;
//     if (readyState === 4 && (status === 200 || status === 201)) {
//       console.log(responseText);
//     }
//   };

//   xhr.open(method, url, true);

//   for (const key in header) {
//     xhr.setRequestHeader(key, header[key]);
//   }

//   xhr.send(JSON.stringify(data));
// }

function ajax({
  url,
  method = 'GET',
  data = {},
  header = { 'Content-Type': 'application/json' },
} = {}) {
  return new Promise((resolve, reject) => {
    try {
      // 可能会发生错误的代码
      const xhr = XMLHttpRequest
        ? new XMLHttpRequest()
        : new ActiveXObject('microsoft.XMLHTTP');

      // 监听state的变化
      xhr.onreadystatechange = () => {
        const { readyState, status, responseText } = xhr;
        if (readyState === 4 && (status === 200 || status === 201)) {
          // 返回成功结果
          resolve(JSON.parse(responseText));
        }
      };

      // 开启连接
      xhr.open(method, url, true);
      //设置请求头
      for (const key in header) {
        xhr.setRequestHeader(key, header[key]);
      }
      // 发送请求 POST => 参数放在请求体中,需要序列化
      xhr.send(JSON.stringify(data));
    } catch (error) {
      // 对错误的处理
      reject(error);
    }
  });
}


<script src="./ajax.js"></script>
  <script>
    // async 修饰函数
    // await 必须搭配async使用
    // async 和await 是回调地狱的终极解决方案

    async function queryGoods() {
      const { data: goods } = await ajax({
        url: 'http://119.91.125.14:8888/home/goods?type=pop&page=1',
      });

      // data: user 别名
      const { data: user } = await ajax({
        url: 'http://119.91.125.14:8888/user/login',
        method: 'POST',
        data: {
          phone: '17602900172',
          password: '123456',
        },
      });

      console.log(goods, user);
    }

    queryGoods();
  </script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值