es6篇
推薦 CrazyCodeBoy的文章 ES六、ES七、ES8特性一鍋燉(ES六、ES七、ES8學習指南)前端
Promise
let
,const
async/await
let
會產生塊級做用域,不會形成變量提高,沒法從新聲明(但能夠從新賦值);const
是常量,如果基本數據類型,具備不變性(沒法從新賦值改動) 引用值能夠調整內部值(可能設計的時候沒有考慮周全!讓 promise 的異步變成同步運行成了可能,await 能夠等到 promise 執行完畢es6
class Animal {
// 構造函數,實例化的時候將會被調用,若是不指定,那麼會有一個不帶參數的默認構造函數.
constructor(name,color) {
this.name = name;
this.color = color;
}
// toString 是原型對象上的屬性
toString() {
console.log('name:' + this.name + ',color:' + this.color);
}
}
var animal = new Animal('dog','white');//實例化Animal
animal.toString();
console.log(animal.hasOwnProperty('name')); //true
console.log(animal.hasOwnProperty('toString')); // false
console.log(animal.__proto__.hasOwnProperty('toString')); // true
class Cat extends Animal {
constructor(action) {
// 子類必需要在constructor中指定super 函數,不然在新建實例的時候會報錯.
// 若是沒有置頂consructor,默認帶super函數的constructor將會被添加、
super('cat','white');
this.action = action;
}
toString() {
console.log(super.toString());
}
}
var cat = new Cat('catch')
cat.toString();
// 實例cat 是 Cat 和 Animal 的實例,和Es5徹底一致。
console.log(cat instanceof Cat); // true
console.log(cat instanceof Animal); // true
複製代碼
模塊的功能主要由 export 和 import 組成。
每個模塊都有本身單獨的做用域,模塊之間的相互調用關係是經過 export
來規定模塊對外暴露的接口,經過import
來引用其它模塊提供的接口。同時還爲模塊創造了命名空間,防止函數的命名衝突。面試
ES6容許在一個模塊中使用export來導出多個變量或函數。ajax
1)導出變量json
//test.js
export var name = 'Rainbow'
複製代碼
2)導出函數api
// myModule.js
export function myModule(someArg) {
return someArg;
}
複製代碼
import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js
複製代碼
箭頭函數所改變的並不是把 this 局部化,而是徹底不把 this 綁定到裏面去;promise
就是 this 是取自外部的上下級做用域(可是又不是常規 function的語法糖)..bash
由於箭頭函數裏並不支持var self = this
或者 .bind(this)
這樣的寫法。app
arguments
,取而代之用rest參數
解決。var foo = (...args) => {
return args[0]
}
console.log(foo(1))
複製代碼
new
一塊兒用就會拋出錯誤。var foo = () => {};
console.log(foo.prototype) //undefined
複製代碼
靜態方法是ES6以後纔有這麼個玩意,有這麼些特色異步
非static
方法無法覆蓋父類class ParentClass {
constructor(name) {
this.name = name;
}
static sayHello() {
console.log("I'm parent!" + this.name);
}
static testFunc(){
console.log('emm...Parent test static Func')
}
}
class SubClass extends ParentClass {
constructor(name) {
super(name);
}
sayChildHello() {
console.log("I'm child " + this.name)
}
static sayHello() {
console.log("override parent method !,I'm sayHello Method")
}
static testFunc2() {
console.log(super.testFunc() + 'fsdafasdf');
}
}
ParentClass.sayHello(); // success print
let a = new ParentClass('test');
a.sayHello() // throw error
SubClass.sayHello(); // 同名 static 能夠繼承且覆蓋
SubClass.testFunc2(); // 能夠繼承
let testA = new SubClass('CRPER');
複製代碼
私有變量
WeakMap能夠避免內存泄露,當沒有被值引用的時候會自動給內存寄存器回收了.
const _ = new WeakMap(); // 實例化,value 必須爲對象,有 delete,get,has,set四個方法,看名字都知道了
class TestWeakMap {
constructor(id, barcode) {
_.set(this, { id,barcode });
}
testFunc() {
let { id,barcode } = _.get(this); // 獲取對應的值
return { id,barcode };
}
}
複製代碼
用Symbol來實現一個私有變量
Promise
和ajax
沒有半毛錢直接關係.promise
只是爲了解決"回調地獄"而誕生的; 平時結合 ajax
是爲了更好的梳理和控制流程...這裏咱們簡單梳理下..
es6 promise ajax
定義
const myHttpClient = url => {
return new Promise((resolve, reject) => {
let client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
function handler() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
}
});
};
使用
myHttpClient('https://www.baidu.com').then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
複製代碼
Promise有三種狀態,Pending/resolve()/reject();
一些須要注意的小點,以下
Pending
轉爲另外兩種之一的狀態時候,狀態不可在改變..Promise
的 then
爲異步.而(new Promise())構造函數內爲同步Promise
的catch
不能捕獲任意狀況的錯誤(好比 then 裏面的setTimout內手動拋出一個Error)Promise
的then
返回Promise.reject()
會中斷鏈式調用 -Promise
的 resolve
如果傳入值而非函數,會發生值穿透的現象Promise
的catch
仍是then
,return
的都是一個新的 Promise
(在 Promise 沒有被中斷的狀況下)Promise 還有一些自帶的方法,好比race,all,前者有任一一個解析完畢就返回,後者全部解析完畢返回...
首先你須要對 promise 有一個清晰的認識,封裝過請求,使用過它的 api 等。
請參考 前端勸退師
的文章 「中高級前端面試」JavaScript手寫代碼無敵祕籍
當你說出 promise.all
和 promise.race
的區別後,面試官可能就會接着考察此題。
/* 使用 async await */
async function queue(tasks) {
const res = []
for (let promise of tasks) {
res.push(await promise(res));
}
return await res
}
queue([a, b, c])
.then(data => {
console.log(data)
})
複製代碼
//Promise
const sleep = time => {
return new Promise(resolve => setTimeout(resolve,time))
}
sleep(1000).then(()=>{
console.log(1)
})
複製代碼
//Generator
function* sleepGenerator(time) {
yield new Promise(function(resolve,reject){
setTimeout(resolve,time);
})
}
sleepGenerator(1000).next().value.then(()=>{console.log(1)})
複製代碼
//async
function sleep(time) {
return new Promise(resolve => setTimeout(resolve,time))
}
async function output() {
let out = await sleep(1000);
console.log(1);
return out;
}
output();
複製代碼
//ES5
function sleep(callback,time) {
if(typeof callback === 'function')
setTimeout(callback,time)
}
function output(){
console.log(1);
}
sleep(output,1000);
複製代碼
Promise 必知必會(十道題): 有助於你更加深入的瞭解 promise 的運行狀況
更多的Promise 詳情能夠參考JavaScript Promise迷你書(中文版);