ES6的相关内容

变量和常量

一般常量用大写

let count = 0
count++
const URL_BASE = "http://"

也可以创建代码块,这样外界就无法访问代码块中的变量

{
    let count = 0
	count++
}

模板字符串

const str1 = "abc"
const str2 = `def${str1}`

如果字符串中要加入别的字符串 ${str1} 一定要用反引号

解构赋值操作

const [a, b, c] = [1, 2, 3]
console.log(a)
console.log(b)
console.log(c)
const{username, age: userage, ...otherinfo} = {
    username: "a",
    age: 1,
    gender: "male",
    school: "SHU"
}
console.log(username)
console.log(userage)
console.log(otherinfo)

注意,剩余项 ...otherinfo 只能写在最后

数组和对象的扩展

扩展运算符

const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 = [...arr1, ...arr2]
console.log(arr3)
const obj1 = {
    a: 1
}
const obj2 = {
    b: 2
}
const obj3= {
    c: 3,
    ...obj1,
    ...obj2
}
console.log(obj3)

数组方法 Array.from(arguments)

一个伪数组

function fn(){
    console.log(arguments)
}
fn(1, 2, 3, 4)

但如果我想要增加一个数字 5 ,就会报错,如下

function fn(){
    console.log(arguments)
    arguments.push(5)
}
fn(1, 2, 3, 4)

所以

function fn(){
    Array.from(arguments).forEach(function(item){
        console.log(item)
    })
}
fn(1, 2, 3, 4)

如果要加元素

function fn() {
    let args = Array.from(arguments) // 转为数组
    args.push(99) // 现在可以用 push 了
    console.log(args)
}
fn(1, 2, 3, 4)

对象的方法 Object.assign()

const objA = {
    name: "myname",
    age: 18
}
const objB = Object.assign({}, objA)
objB.name = "a"
console.log(objA, objB)

class

class A{
    constructor(name, age){
        this.name = name
        this.age = age
    }
    introduce(){
        console.log(this.name)
        console.log(this.age)
    }
}
const a1 = new A("myname", 18)
a1.introduce()
class B extends A {
  constructor(name, age, gender) {
    super(name, age)
    this.gender = gender
  }
  sayHello() {
    console.log('你好我是' + this.name)
  }
}
const b1 = new B('小李', 19, '女')
console.log(b1)
b1.sayHello()
b1.intruduce()

箭头函数

const gerSum1 = n => n + 3
console.log(gerSum1(10))
const gerSum2 = (n1, n2) => n1 + n2
console.log(gerSum2(10, 20))
const gerSum3 = (n1, n2, ...others) => console.log(n1, n2, others)
console.log(gerSum3(10, 20, 30, 40, 50))

Promise 异步处理

console.log("1")
console.log("2")
setTimeout(()=>{
    console.log("3")
}, 1000)
console.log("4")

先把同步的 1, 2, 4 执行完,再执行异步的 3

异步任务会在当前存在的同步任务都执行完之后,再去执行

如果存在很多异步同步,就会嵌套成这样

console.log('任务1:...同步')
console.log('任务2:...同步')
setTimeout(() => {
  console.log('任务3:...异步')
  console.log('任务4:...同步')
  setTimeout(() => {
    console.log('任务5:...异步')
    console.log('任务6:...同步')
    setTimeout(() => {
      console.log('任务7:...异步')
      console.log('任务8:...同步')
    }, 3000)
  }, 3000)
}, 3000)

Promise 能够将这种复杂的嵌套式的异步结构书写为一种更接近于同步的写法

const p1 = new Promise((resolve, reject) => {
    
})
console.log(p1)

输出

Promise {<pending>}

其中, resolve 理解为成功时运行的一个工具, reject 理解为失败时运行的一个工具

我们在执行程序时,会有成功和失败

例如,我们向服务端请求一条数据,如果我们拿到的是一个正确的数据,那就是成功的;如果我们拿到的是一个错误的数据,比如给服务端的身份认证信息没有通过、请求次数过多、超时等,那么我后续的就不能执行,这就是失败的。

我们所创造的实例 p1 就标记了我们在 new promise 中所涉及的代码功能中的异步任务最终的处理结果,他最终会通过回调的方式再返还到 p1 这个位置上,然后就可以利用它继续进行后续的处理。

const p1 = new Promise((resolve, reject) => {
    resolve()
})
console.log(p1)

输出

Promise {<fulfilled>: undefined}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

fulfilled 代表运行成功

const p1 = new Promise((resolve, reject) => {
    reject()
})
console.log(p1)

输出

Promise {<rejected>: undefined}
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: undefined

rejected 代表运行失败

继续利用 p1

p1.then(data => {
    
})

表示在我成功的时候给我们传递一个成功或失败数据,例如:

const p1 = new Promise((resolve, reject) => {
    resolve("运行成功得到的数据")
    // reject("运行失败得到的数据")
})
p1.then(data => {
    console.log(data)
})
.catch(err => {
    console.log(err)
})

其中, Promise 里的是同步, .catch.then 是异步

如果是需要两个异步任务

const p1 = new Promise((resolve, reject) => {
    resolve("运行成功得到的数据")
    // reject("运行失败得到的数据")
})
p1.then(data => {
    console.log(data)
    return new Promise((resolve, reject) => {
        resolve("运行成功得到的数据")
        // reject("运行失败得到的数据")
    })
})
.then(data => {
    console.log(data)
})
.catch(err => {
    console.log(err)
})
const p1 = new Promise((resolve, reject) => {
    // resolve('任务1:成功得到的数据')
    reject('任务1:失败的信息')
})

p1.then(data => {
    console.log(data)
    return new Promise((resolve, reject) => {
        resolve('任务2:成功得到的数据')
        // reject('任务2:失败的信息')
    })
}, err => {
    console.log('任务1:失败了')
    throw new Error('任务1失败')
})
.then(data => {
    console.log(data)
}, err => {
    console.log('任务2:失败了')
})

async 异步处理的语法糖

一种基于 promise 的异步操作的简化功能,但不能完全替代 promise

async 要搭载 await 关键词使用

function A(){
    return new Promise((resolve, reject) => {
        const judge = true
        if(judge){
            resolve("任务2处理成功")
        }
        else{
            reject("任务2处理失败")
        }
    })
}
async function main(){
    console.log("任务1")
    console.log(await A())
    
    console.log("任务3")
}

proxy 代理

<!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>
    <div id="container">默认内容</div>
    <script src="main.js"></script>
</body>
</html>
const obj = {
    name: "myname",
    age: 18
}
const container = document.getElementById("container")
container.textContent = obj.name
obj.name = "abc"
container.textContent = obj.name

每次更改内容,都要加上 container.textContent = obj.name 这行代码

const obj = {
    name: "myname",
    age: 18
}
const p1 = new Proxy(obj, {
    get(target, property){
        return obj[property]
    },
    set(target, property, value){
        obj[property] = value
        container.textContent = obj.name
    }
})
p1.age = 21
p1.name = "jack"

Moudle

有两种类型,分别是 ESMCommonJS

EMS

a.js

export const aTitle = "a标题"
export function aFn(){
    console.log("a函数")
}
export default{
    name: "a模块"
}

b.js

export const bTitle = "b标题"
export function bFn(){
    console.log("b函数")
}
export default{
    name: "b模块"
}

main.js

import moduleA from "./a.js"
import moduleB from "./b.js"
import {aTitle, aFn} from "./a.js"
import {bTitle, bFn} from "./b.js"
console.log(moduleA) // a.js的默认内容
console.log(moduleB) // b.js的默认内容
console.log(aTitle) // a标题
aFn() // a函数
console.log(bTitle) // b标题
bFn() // b函数

index.html

<!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>
    <div id="container">默认内容</div>
    <script src="main.js" type="module"></script>
</body>
</html>

CommonJS

c.js

MediaSourceHandle.exports = {
    a: 1,
    b: 2,
    c: 3
}

main.js

const moduleA = require("./c.js")
console.log(moduleA)

在终端中运行

node main.js

注意本机要安装 Node.js ,否则运行不成功

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐