ES5 只有两种声明变量的方法:var命令和function命令。ES6 除了添加let和const命令,后面章节还会提到,另外两种声明变量的方法:import命令和class命令。所以,ES6 一共有 6 种声明变量的方法。
1、let 取代 var 定义变量,
块级作用域(变量不会跑到定义的外面去),不能重复申明,不存在变量提升
循环中(for)用let
{
let num = 20;
}
console.log(num); // unm is not defined
2、const 定义常量,一定义就会初始化,不能重复定义。它是只读,对象,不可修改
const MAX = 10;
3、用` `定义多行字符串,加变量 ${a}
let a = 123
let str = `
这是另一行文本${a}
这是再一行文本`
4、箭头函数
const add = (num1,num2) => {
return num1*num2
}
可以精简为:
const add = (num1, num2) => return num1*num2
相当于:
const add = function(num1, num2){
return num1*num2
}
5、箭头函数中,没有arguments, 没有this。如果你在箭头函数中使用了this,那么该this一定就是外层的this。
要解决这个this问题,要用对象的单体模式,show: function (){} --> show(){}
6、...来表示展开运算符,它可以将数组方法或者对象进行展开。
let arr = [5,6]
console.log([1,3,5,...arr])
7、数组的解析结构
const arr = [1, 2, 3];
const [a, b, c] = arr;
8、函数简写
show: function (){} --> show(){}
9、模块化
import export export default
export const sum = (x, y) => x + y
import { sum } from 'aa'
export default (x, y) => x + y
import x form 'aa' //可以取任意名字
10、构造函数的方式创建对象(首字母大写)----ES5的写法
function Animal(name, age) {
this.name = name;
this.age = age;
}
//构造方法
Animal.prototype.showname = function () {
console.log(111,this.name)
}
var dog = new Animal()
dog.name = "zhangsan";
*****//ES6的新写法
class Animal{
constructor(name, age){ //构造器,初始化属性
this.name = name;
this.age = age;
} //此处一定是无符号的
showName(){ //构造方法
console.log(123, this.name);
}
}
var dog = new Animal("zhansan22", 19);
dog.showName();
RE: JavaScript开发笔记