1、let 和 const 命令
let:块级作用域变量,const:常量
首先,let 和 const,不存在变量提升。
* 使用时,先声明,后调用。
console.log(a); //全局变量:undefined
console.log(b,c);
var a = 1;
let b = 2;
const c = 3
同时,相同作用域内,不能重复声明
//报错
let b = 1;
let b = 2;
//报错
var c = 10
const c = 20;
//不报错
let i = 15;
for(let i of "abc"){
console.log(i)
}
const,声明一个只读的常量,一旦声明,常量值就不能修改。
//报错
const cst; //Missing initializer in const declaration
cst = 15;
//报错
const name = "mark"; // Assignment to constant variable.
name = "others";
```
最后:
```javascript:run
var a = 1;
console.log(window.a) //1
let b = 1;
console.log(window.b) // undefined
const c = 10;
console.log(window.c) // undefined
在ES6 中,let、const、class声明的全局变量,不属于顶层对象的属性。但为了兼容,var 、function 申明的全局变量,依然是顶层对象的属性。
通俗点说,声明的 var、function ,默认会挂到window上;但在ES6中,let、const、class 并不是挂在window上。可 console.log(window) 查看。
2、变量的解构赋值
解构的定义是:从数组和对象中提取值,对变量进行赋值。
数组:
var [a,b,c='4',d='5'] = [1,2,3];
console.log(a,b,c,d)
对象:
* 当变量名与属性名不一致,必须写成这样:var {属性名:变量名} = {属性名:值}
var {a,b,c="5",d:alias,e:nickname="6",f:end="7"} = {a:1,b:2,c:3,d:4,e:undefined};
console.log(a,b,c,alias,nickname,end)
1)、对于一个已经声明的变量,用于解构赋值,需注意:
报错:
var a;
{a} ={a:1};
console.log(a)
正解,需要在表达式外面加一层括号:
var a;
({a} ={a:1});
console.log(a)
2)、对数组进行对象属性的解构
数组本质上是特殊的对象,故这里可以对数组进行对象属性的解构:
var arr = [1,2,3];
let {0:first,1:second,[arr.length-1]:third } = arr;
console.log(first,second,third)
3)、交换变量的值
var a = 1,
b = 2;
[a,b]=[b,a];
console.log(a,b)
字符串:
const [x,y,z] = "today";
console.log(x,y,z)
3、class 类
1)、constructor(构造方法)和get、set
constructor(构造方法),由ES5的构造函数演变而来。
新的class写法,会让对象原型的结构更加清晰、更像面向对象编程的语法。
class Human {
constructor(x,y){
this.name = x;
this.age= y;//"white"
}
total() {
return this.name+" : "+this.age;
}
get info(){
return this.name
}
set info(val){
this.name = val
}
}
const human = new Human("marc",15);
console.log(human.name);
console.log(human.total());
//取值函数和存值函数:get、set
human.info = "21";
console.log(human.info);
2)、继承(extends)和静态方法(static)
父类的静态方法,会被子类继承
class Human{
constructor(x,y){
this.name = x;
this.age= y
}
static staticHuman(){
return "staticHuman"
}
total() {
return this.name+" : "+this.age;
}
}
console.log(Human.staticHuman)
class Robot extends Human{
constructor(x, y,w) {
super(x, y);
this.sexy = w
}
}
var robot = new Robot("tang",15,"male");
console.log(Robot.staticHuman());//父类静态方法
console.log(robot.total()); //父类方法
console.log(robot.sexy);
4、Promise
待续...