ES6 常用语法总结
1.let/const
es6语法中,变量的声明方式改变了,而新的声明方式也带来了一些新的特性,其中最重要的就是块级作用域和不再具有变量提升
我们都是到,用var声明的变量会变成一个全局变量,但是用let和const申声明的变量就只能在当前作用域使用,例如:
{
var a = 20;
}
console.log(a) //20
{
let a = 20;
}
cosnole.log(a)//a is not defined
同时,let 和 const声明的变量也不再具有变量提升
这里还有一个很有意思的事情,当let和for结合起来的时候会发士一个很有意思的化学反应
如下代码:
for(var i = 0; i<6 ;i++){
setTimeout(function(){
console.log(i)
},i*1000)
}
//输出 6 6 6 6 6 6
for(let i = 0; i<6 ;i++){
setTimeout(function(){
console.log(i)
}, i*1000)
}
//输出:0 1 2 3 4 5
还有就是变量提升,let 和 const 定义的变量不可以在使用后再声明
这里我们也得注意一下 let 和 const 的区别
- let 定义的是一个变量,而 const 定义的是一个常量,是不可改变的
- const 声明的常量必须初始化,而 let 声明的变量可以不用初始化
二、箭头函数的使用
以前我们写函数是这样写的
var add = function (a,b){
return a+b;
}
//现在我们可以这样写
var add = (a,b) => a+b
箭头函数可以替换掉函数表达式,但是不能替换函数声明
其次,箭头函数还有一个很重要的特性,那就是箭头函支持 this ,箭头函数中没有this,因为箭头函数中没有this,因此我们也就不再需要 call /apply/bind 来指定this 的指向,如果你在箭头函数中使用了this,那么这个this 就是外层的this。
还有值得注意的是this函数也不再具有 argument 对象
三、解析结构
这件简单的举个例子
const obj = {
name :"jack",
age:20,
sex:"man"
}
//以前我们是这样写的
var name = obj.name
var age = obj.age
//ES6这样写
let {name,age} = obj
四、默认参数
之前我们不能为函数指定一个默认参数。ES6则为我们解决了这样的问题
function add(a,b){
var a = a || 10
var b = b || 20
return a + b
}
//ES6
function add(a = 10,b = 20){
return a + b
}
五、展开运算符( … )
在es6中我们用 … 表示展开运算符,它可以将一个数组或者对象展开
例如:用于数组的拼接
var arr1 = [1,2,3]
var arr2 = [...arr1,4,5]
console.log(arr2) //[1,2,3,4,5]
展开对象
const obj1 = {
a :1,
b :2,
c :3,
}
const obj2 = {
...obj1,
d:4;
}
六、剩余参数
在我们对于要传入函数的参数数量未知时,可以采用剩余参数来表示
function add(...num){
let sum = 0;
num.map(item => sum+=item)
return sum;
}
console.log(add(1,2,3,4))//10
七、对象字面量
ES6针对函数字面量做了很多的简化处理下面来简单的举几个例子
-
当属性与值同名时
//ES5 const obj = { name: name, age:age } //ES6 const obj = { name, age }
-
方法也可以简写
//ES5 const obj = { name: name, age:age, getName:function getName{ return this.name } } //ES6 const obj = { name, age, getName(){ return this.name } }
八、class实现继承
在不使用class的情况下,我们时这样来实现继承的:
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.getName = function(){
return this.name
}
function Student(name,age,number){
Person.call(this,name,age)
this.number = number
}
function temp(){}
temp.prototype = Person.prototype
Student.prototype = new temp()
Student.prototype.constructor = Student
Student.prototype.getNumber = function(){
return this.number
}
let student = new Student("张三",20,"001")
console.log(student.getNumber())//"001"
console.log(student.getName())//"张三"
使用class我们这样来实现继承
class Person {
constructor(name,age){
this.name = name
this.age = age
},
getName(){
return this.name
}
}
class Student extends Person {
constructor(name,age,number){
super(name,age)
this.number = number
}
getNumber(){
return this.number
}
}