ES 6
class 類
-
類和傳統(tǒng)的構(gòu)造函數(shù)對(duì)比
//傳統(tǒng)函數(shù)的寫法 function Point(x,y){ this.x=x; this.y=y; } Point.prototype.toString=function(){ return `${this.x},${this.y}` } // 語(yǔ)法糖class的書寫 class Point{ constructor(x,y){ this.x=x; this.y=y } toString(){ return `${this.x},${this.y}` } } //Point.prototype.constructor===Point true //typeof Point function
解析:
constructor
方法里面的相當(dāng)于構(gòu)造函數(shù)里面的部分,toString
方法相當(dāng)于原型中狸驳,方法和方法之間不能有逗號(hào),否則會(huì)報(bào)錯(cuò)秋泄。?
Promise構(gòu)造函數(shù)
-
簡(jiǎn)單模擬Promise的構(gòu)造函數(shù)寫法
class Promise{ constructor(){ this.callbacks = [] } then(onsuccess,onfail){ // 儲(chǔ)存一個(gè)對(duì)象里面有2中狀態(tài)持隧,一種是成功谱净,一種是失敗 this.callbacks.push({ resolve: onsuccess, reject: onfail }) return this //鏈?zhǔn)秸{(diào)用then p1.then().then().... } resolve(result){ this.complete('resolve',result) } reject(result){ this.complete('reject',result) } complete(type,result){ const callbackObj = this.callbacks.shift() //拿出數(shù)組第一個(gè)對(duì)象 callbackObj[type](result) } } //調(diào)用這個(gè)Promise構(gòu)造函數(shù) let p = new Promise() function fn() { console.log('fn1') setTimeout(()=>{p.resolve('data1')},1000) console.log('第一個(gè)setTimeout之后') return p } function fn1(result){ console.log('fn1',result) setTimeout(() =>{p.resolve('data2')},2000 ) } function fn2(result){ console.log('fn2',result) } fn().then(fn1).then(fn2) //相當(dāng)于數(shù)組里面存放2個(gè)對(duì)象 // [{resolve:fn1,reject:undefined},{resolve:fn2,reject:undefined}] //then方法返回的是一個(gè)新的Promise實(shí)例(注意放闺,不是原來那個(gè)Promise實(shí)例)凶赁。因此可以采用鏈?zhǔn)綄懛ü畚希磘hen方法后面再調(diào)用另一個(gè)then方法臊恋。
-
Promise()知識(shí)點(diǎn)
?
-