一.新变量声明方式
使用let/const声明,两个特性:提供了块级作用域与不再具备变量提升。
let–>声明变量,const–>声明常量。
二.箭头函数
1 | // ES5 |
箭头函数可以替换函数表达式,不能替换函数声明
箭头函数中没有this,如使用则是外部this,故无从谈起call/bind/apply来改变this指向
箭头函数中没有arguments对象
三.模板字符串
1 | // ES6 |
使用${}来包裹一个变量或者表达式。
四.解析结构
1 | const props={ |
获取clicked和loading属性:1
2
3
4
5
6
7// ES5
var loading = props.loading;
var clicked = props.clicked
// ES6
const {loading,clicked} = props;
// 给一个默认值,当props对象中找不到loading时,loading等于默认值
const {loading = false,clicked} = props;
数组解析结构:1
2
3
4
5
6
7
8// ES6
const arr = {1,2,3};
const [a,b,c] = arr;
// ES5
var arr = [1,2,3];
var a=arr[0];
var b=arr[1];
var c=arr[2];
五.函数默认参数
1 | // ES6默认参数写法 |
六.展开运算符
在ES6中使用…表示展开运算符,可以将数组和对象进行展开。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// 展开数组
const arr1=[1,2,3];
const arr2=[...arr1,4,5,6]; // 即[1,2,3,4,5,6]
// 展开对象
const obj1={
a:1,
b:2,
c:3
}
const obj2={
...obj1,
d:4,
e:5,
f:6
}
console.log(obj2); // {a:1,b:2,c:3,d:4,e:5,f:6}
在解析结构中的使用1
2
3
4
5
6const props={
size:1,
src:xxx,
mode:'si'
}
const {size,...others} = props;
作为函数的不定参,只有放在最后,才能作为不定参1
2
3
4
5// 所有参数之和
const add = (a,b,...more)=>{
return more.reduce((m,n)=>m+n) + a + b;
}
console.log(add(1,23,1,2,3,4,5)); // 39
七.对象字面量与class
ES6简化了对象字面量语法。
1
2
3
4
5
6
7
8
9
10
11
12const name = 'Jane';
const age = 20
// es6
const person = {
name,
age
}
// es5
var person = {
name: name,
age: age
};可以在模块对外提供接口的时候使用:
1
2
3
4
5
6const getName = () => person.name;
const getName = () => person.age;
// commonJS方式
module.exports = {getName,getAge};
// ES6的modules形式
export default {getName,getAge};可以简写对象字面量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// es6
const person = {
name,
age,
getName() { // 简写了对象内函数,只要不使用箭头函数,this就还是我们熟悉的this
return this.name
}
}
// es5
var person = {
name: name,
age: age,
getName: function getName() {
return this.name;
}
};对象字面量中可以使用中括号作为属性,属性名可以是一个变量
1
2
3
4
5
6const name = 'Jane';
const age = 20;
const person = {
[name]: true,
[age]: true
}class => ES6新的语法糖,与面向对象的写法不同,思想一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23// ES5构造函数
function Person (name,age){
this.name = name;
this.age = age;
}
// 原型方法
Person.prototype.getName = function(){
return this.name;
}
// ES6方法
class Person{
constructor(name,age){ //构造函数
this.name = name;
this.age = age;
}
getName(){ // 将方法添加到原型中
return this.name;
}
static a = 20; //等同于Person.a = 20;
c = 20; //表示在构造函数中添加属性,类似于构造函数中 this.c = 20;
// 箭头函数写法表示在构造函数中添加方法,构造函数中类似于this.getAge = function(){}
getAge = () => this.age;
}
关注箭头函数的this指向,箭头函数的this指向不能被改变。react组件中利用this不改变特性在不同组件之间传值。
- extends实现继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
getName(){
return this.name;
}
}
// Student类继承Person类
class Student extends Person {
constructor(name,age,gender,classes){
super(name,age); //必须调用一次,表示构造函数的继承
this.gender = gender;
this.classes = classes;
}
getGender(){
return this.gender;
}
}
使用继承的时候明确是构造函数的继承还是原型的继承。
使用super可以调用原型中的方法,如super.getName;
参考文章:
ES6常用知识合集——这波能反杀
如有错误,烦请指正,谢谢!