1. let
let其实和var十分相似,其中要重点记忆的有:
- let没有声明前置,不可先使用再声明也不可重复声明
- let存在块级作用域,例如:
for(let i = 0; i < 3; i ++) {
console.log(i) // 没问题
}
console.log(i) // 报错,因为i的作用域只在for循环内
2. const
const是用来声明常量的,即一旦声明赋值后就不能改变了,let适用的同样适用于const
3. 解构赋值
- 数组的解构赋值
可以简化给数组赋值的写法
例如:
let [a, b, c] = [1, 2, 3]
console.log(a, b, c) // 1,2,3
有默认值的情况:
let [a, b = 2, c] = [1, , 3]
console.log(a, b, c) // 1,2,3
- 对象的解构赋值
同样可以简化对象的赋值写法
例如:
let [name, age] = ['lee', '22']
let obj1 = {name, age} // 相当于: obj1= {name: name, age: age}
console.log(obj1) // {name: 'lee', age: '22'}
有默认值的情况:
{x, y = 2} = {x: 1, y}
// {x: 1, y: 2}
- 函数的解构赋值
可以设置没有该参数时的默认值
function add ([x = 1, y = 2]) {
return x+ y
}
add([]) // 3
add([2]) // 4
add([ , 3]) // 4
4. 模板字符串 ``
- 多行字符串拼接可以更方便阅读和书写:
`
<div>
<ul>
<li><p></p></li>
<li><p></p></li>
</ul>
</div>
`
- 带有变量的字符串模板拼接,只需要将变量用${}包含起来即可
let name = 'lee'
`my name is ${name}` // my name is lee
5. 扩展运算符 ...
let a = [1, 2]
console.log(...a) // 1,2
// 添加新项
console.log(...a, 3) // 1,2,3
相当于Array.contcat()
也可以用于函数的参数,简化传参的写法
6. 模块化 import , export
方便代码的拆分和复用,更轻松的实现按需加载,例如:
// a.js
let a = 2
export {a} // 解构赋值,相当于{a: 2}
// b.js
import {a} form 'a.js'
console.log(a) // 2
7. class和继承
- class
本质上并没有class类这个概念,只是将函数进行包装后的一种语法糖。。。
class Person {
// 构造函数
constructor (name, age) {
// this指向当前的Person函数,增加并复制name和age属性
this.name = name
this.age = age
}
this.print()
// 该Person内的方法
print() {
console.log(this.name) // lee
console.log(this.age) // 22
}
}
new Person('lee', 22)
- 继承
使用extends, super
class Child extends Person {
constructor (name, age, sex) {
// super可以获取被继承的class的相关属性
super(name, age)
this.sex = sex
}
this.print()
// 该Person内的方法
print() {
console.log(this.name) // lee
console.log(this.age) // 22
console.log(this.sex) // male
}
}
new Child('lee', 22, 'male')