目录
一、新的变量声明方式 let/
与var不同,新的变量声明方式带来了一些不一样的特性,其中最重要的两个特性就是提供了块级作用域与不再具备变量提升。
通过2个简单的例子来说明这两点。
{
let a = 20;
}
console.log(a); // a is not defined
而这个简单的例子,会被编译为:
{
let _a = 20;
}
console.log(a); // a is not defined
// ES5
console.log(a); // undefined
var a = 20;
// ES6
console.log(a); // a is not defined
let a = 20;
二、 箭头函数的使用
(1)语法不同
// es5
var fn = function(a, b) {
return a + b;
}
// es6 箭头函数写法,当函数直接被return时,可以省略函数体的括号
const fn = (a, b) => a + b;
(2)箭头函数中,没有this.
- 还有一个至关重要的一点,那就是箭头函数中,没有this。如果你在箭头函数中使用了this,那么该this一定就是外层的this。
三、模板字符串
// es6
const a = 20;
const b = 30;
const string = `${a}+${b}=${a+b}`;
// es5
var a = 20;
var b = 30;
var string = a + "+" + b + "=" + (a + b);
四、解构赋值
// 首先有这么一个对象
const props = {
className: 'tiger-button',
loading: false,
clicked: true,
disabled: 'disabled'
}
// es5
var loading = props.loading;
var clicked = props.clicked;
// es6 解析结构
const { loading, clicked } = props;
五、函数默认参数
- 之前我们不能直接为函数指定默认参数,因此很多时候为了保证传入的参数具备一个默认值,我们常常使用如下的方法:
function add(x, y) { var x = x || 20; var y = y || 30; return x + y; } console.log(add()); // 50
六、展开运算符
- 在ES6中用…来表示展开运算符,它可以将数组方法或者对象进行展开。先来看一个例子它是如何使用的。
const arr1 = [1, 2, 3]; const arr2 = [...arr1, 10, 20, 30]; // 这样,arr2 就变成了[1, 2, 3, 10, 20, 30];
七、对象字面量与class
-
1. ES6针对对象字面量做了许多简化语法的处理。
当属性与值的变量同名时。const name = 'Jane'; const age = 20 // es6 const person = { name, age } // es5 var person = { name: name, age: age };
2.class
- ES6为我们创建对象提供了新的语法糖,这就是Class语法。如果你对ES5中面向对象的方式比较熟悉的话,Class掌握起来也是非常迅速的,因为除了写法的不同,它并不会增加新的难以理解的知识点。我们先利用一个简单的例子来看看写法的不同。
// 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 } }
3.继承 extends
相比ES5,ES6的继承就要简单很多,我们直接来看一个例子。
class 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; } }