JavaScript|ES6语法

发布时间 2023-07-11 09:55:53作者: Weltㅤ

1 箭头函数

1) 语法

const fn = (参数) => {
  函数体
}
const fn = (x) => x + 1

简写

 const fn = (x) => x + 1

函数体中只有一行return

  • 可以同时省略{}return

2) 示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const add = (x, y) => {
        return x + y
      }

      console.log(add(1, 2))

      // 当代码比较简单时, 只有一个return
      // 可以同时省略{}和return

      const fn = (x, y) => x + y
    </script>
  </body>
</html>

2 解构赋值

1) 对象的解构

基础语法

const {属性名1, 属性名2} = 对象

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const obj = {
        name: 'xiaoming',
        // ES6中方法的简写
        sayHi() {
          console.log('hi')
        },
      }
      // 定义了两个普通变量
      //   1. 根据对象的属性名解构
      //   2. 不是根据对象属性的顺序
      const { name, sayHi } = obj
      console.log(name)
      sayHi()

      // const name = obj.name
      // const sayHi = obj.sayHi
    </script>
  </body>
</html>

默认值

const {属性名1=默认值, 属性名2...} = 对象

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const obj = {
        name: 'xiaoming',
        gf: {
          name: 'xiaomei',
        },
      }
      // 给不存在的属性赋初始值
      const { name = 'new', age = 20 } = obj
      console.log(name, age) // xiaoming 20
    </script>
  </body>
</html>

别名

const {属性名1:别名, 属性名2:别名} = 对象

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const obj = {
        name: 'xiaoming',
        gf: {
          name: 'xiaomei',
        },
      }

      const {
        name,
        gf: { name: gfName },
      } = obj
      console.log(name, gfName) // xiaoming xiaomei
    </script>
  </body>
</html>

2) 数组的解构

基础语法

const [变量名1, 变量名2, ...] = 数组

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const arr = ['red', 1, true]

      // 数组的解构: 根据数组元素的顺序
      const [a, b, c, d = 100] = arr
      console.log(a, b, c, d)
      // 展开运算符..., 剩余参数
      const [red, ...res] = arr
      console.log(red, res)
    </script>
  </body>
</html>

3 class定义类

1) 基础语法

class 类名 {
  constructor() {
    // 属性
  }
  方法1
  方法2
}

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 定义类
      class Person {
        constructor(n, a) {
          // 构造函数: 完成属性的初始化
          this.name = n
          this.age = a
        }
        // 定义方法
        getName() {
          return this.name
        }
      }

      // 根据类创建实例对象
      const p1 = new Person('xiaoming', 20)
      console.log(p1)
      console.log(p1.getName())

      const { name } = p1
      console.log(name)
    </script>
  </body>
</html>

5 promise对象

1) 属性

promise对象有两个属性

  • 状态
  • 结果

状态

状态有三种

  • pending: 准备
  • fulfilled: 成功
  • rejected: 失败

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 创建一个promise对象
      //  1. Promise接收一个函数作为参数
      //  2. promise对象(属性和方法)
      //      - 状态 pending, fulfilled, rejected
      //      - 结果

      // 3. promise状态的改变是单向, 不可逆, 状态的改变是一次性
      // 只能从pending => fulfilled / rejected
      const p1 = new Promise((resolve, reject) => {
        // 当调用resolve函数, 当前promise对象的状态从 pending => fulfilled(成功)
        resolve()
        // 当调用reject函数, 当前promise对象的状态从 pending => rejected(失败)
        reject()
      })
      console.log(p1)
    </script>
  </body>
</html>

2) 方法

then方法

then方法中, 可以获取promise对象的结果

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const p1 = new Promise((resolve, reject) => {
        // resolve('p1的结果')
        reject('p1出错')
      })
      const p2 = p1.then(
        (value) => {
          // 1. 语法错误
          // console.log(a)
          // 2. throw 抛出一个错误
          // throw new Error('错误')
          return 123
        },
        () => {}
      )
      p2.then(
        (value) => {
          console.log(1, value)
        },
        () => {
          console.log(2)
        }
      )
      // console.log(p2)

      // p2的状态是由p1的成功/失败的回调决定
      //    如果在函数中没有报错, 那么p2的状态就是 成功
      //    如果在函数中有报错, 那么p2的状态就是 失败
      // p2的结果由函数的返回值确定
    </script>
  </body>
</html>

3) async...await

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // async: 写在函数的前面
      //  1. 可以单独使用.
      //  2. 将返回值包装成一个promise对象
      async function foo() {
        // return Promise.resolve(123)
        return 123
      }
      console.log(foo())

      // 获取123的值
      foo().then((value) => {
        console.log(value)
      })

      // await: 后面跟一个promise
      //  1. 不能单独使用. 配合async使用
      //  2. 表达式的值 就是 promise的结果

      async function test() {
        // 如果await后面不是一个promise对象, 会自动转换成promise对象
        const res = await foo()
        console.log(res)
      }
      test()
    </script>
  </body>
</html>

6 ES Module

1) 导出

在一个js文件中, 通过export导出

  • 变量
  • 函数

示例

// 导出变量
export const str = 'str'

// 导出函数
export function foo() {
  console.log('foo')
}

// 导出类
export class Person {
  constructor(n) {
    this.name = n
  }
}

2) 导入

在一个js文件中, 通过import导入

在一个html文件中, 通过<script type="module">导入

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script type="module">
      // 1. 通过 export 导出
      // 2. 通过 import 导入
      import { str, foo, Person } from './01-test.js'
      console.log(str)
      foo()
      const p = new Person('xiaoming')
      console.log(p)
    </script>
  </body>
</html>

3) 默认导入导出

默认导出

在一个js文件中, 使用export default默认导出

// 默认导出
export default function () {
  console.log('hello')
}

⚠️ 注意

一个模块只能有一个默认导出

// 默认导出
export default function () {
  console.log('hello')
}

// 一个模板只能存在一个默认导出, 会报错
export default function bar () {
  console.log('bar')
}
img

默认导入

通过import语法, 在模块A中导入模块B

// 不写括号: 表示导入 另一个模块中 默认导出的内容
import fn from './02-默认导出.js'
console.log(fn)

总结

  1. 导入时加括号, 表示普通导入, 使用export导出

  2. 导入时 箭头函数