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
待續...