ES6初步學(xué)習(xí)
在ES5里只有全局作用域和函數(shù)作用域的區(qū)分式廷,會(huì)造成一些定義的內(nèi)容被覆蓋掉 就像for循環(huán)定義事件這種情況會(huì)出現(xiàn)
var name="output";
var a=2;
if(a>1){
var name="input";
console.log(name);
}
console.log(name);
ES6 let/const
let 起到了一個(gè)塊級(jí)作用域的作用,再出了所在{}后在使用let所定義的東西就會(huì)失效
let name="output";
let a=2;
if(a>1){
let name="input";
console.log(name);
}
console.log(name);
利用let可以解決循環(huán)取值的問題
for(let i=0;i<6;i++){
document.getElementsByTagName("li")[i].onclick=function(){
console.log(i);
}
}
console.log(i);//報(bào)錯(cuò)——因?yàn)槌隽藟K級(jí)作用域子寓,所以就不管用了。
const 用來定義的變量不可更改
const i=5;
i="s";
console.log(i);
const有一個(gè)很好的應(yīng)用場(chǎng)景笋除,就是當(dāng)我們引用第三方庫的時(shí)聲明的變量斜友,用const來聲明可以避免未來不小心重命名而導(dǎo)致出現(xiàn)bug:
ES6中還引入了類的概念,這樣面向?qū)ο蟮膶?shí)現(xiàn)變得也更加容易了
class 創(chuàng)建一個(gè)類
class Animal{
constructor(){//構(gòu)造函數(shù)
this.type="amimal"
}
says(say){
console.log(this.type+ "says" +say);
}
}
let animal=new Animal();
animal.says('hello');
class Cat extends Animal{//extends 關(guān)鍵字代表繼承垃它,
constructor(){
super();//鲜屏!子類創(chuàng)建必有!super指代父類的實(shí)例(this對(duì)象) 国拇,因?yàn)樽宇悰]有自己的this對(duì)象洛史,二是繼承父類的this.——不調(diào)用則會(huì)顯示 this is not defined 。
this.type="cat";
}
}
let cat=new Cat();
cat.says("!miao!miao");
function函數(shù)運(yùn)用
函數(shù)作為最常用的在這里被簡(jiǎn)化為 箭頭函數(shù) =>
var a=function(one){ return one++; }//ES5
let b=one=>{one++};
當(dāng)我們使用箭頭函數(shù)時(shí)贝奇,函數(shù)體內(nèi)的this對(duì)象虹菲,就是定義時(shí)所在的對(duì)象,而不是使用時(shí)所在的對(duì)象掉瞳。并不是因?yàn)榧^函數(shù)內(nèi)部有綁定this的機(jī)制毕源,實(shí)際原因是箭頭函數(shù)根本沒有自己的this,它的this是繼承外面的陕习,因此內(nèi)部的this就是外層代碼塊的this霎褐。
destructuring解構(gòu)賦值
自動(dòng)解析數(shù)組或?qū)ο笾械闹担热缛粢粋€(gè)函數(shù)返回多個(gè)值该镣,常規(guī)是返回一個(gè)
/*__ES5__*/
var send="pen";
var receive="paper";
var thing={send:send,receive:receive};
console.log(thing);//Object {send: "pen", receive: "paper"}
/*____ES6____*/
let senda="pen";
let receivea="paper";
let Thing={senda,receivea};
console.log(Thing)//Object {send: "pen", receive: ""paper"}效果一樣冻璃,但是卻減少了代碼量。
default 默認(rèn)值
傳統(tǒng)指定默認(rèn)參數(shù)的方式
function sayHello(name){
var name=name||'dude';
console.log('hello'+name);
}
字符串模板
字符串模板相對(duì)簡(jiǎn)單易懂些损合。ES6中允許使用反引號(hào) ` 來創(chuàng)建字符串省艳,此種方法創(chuàng)建的字符串里面可以包含由美元符號(hào)加花括號(hào)包裹的變量${vraible}
運(yùn)用ES6的默認(rèn)參數(shù)
function saysHello2(name='dude'){
console.log('hello $ {name}');
}
sayHello();//Hello dude
sayHello('wayou');//Hello wayou
sayHello2();//Hello dude
sayHello2('wayou');//Hello wayou