美文网首页
ES 6(持续更新)

ES 6(持续更新)

作者: sunny519111 | 来源:发表于2017-05-05 17:52 被阅读51次

ES 6

class 类

  1. 类和传统的构造函数对比

    //传统函数的写法
    function Point(x,y){
      this.x=x;
      this.y=y;
    }
    Point.prototype.toString=function(){
      return `${this.x},${this.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方法里面的相当于构造函数里面的部分, toString方法相当于原型中,方法和方法之间不能有逗号,否则会报错。

    Promise构造函数

    1. 简单模拟Promise的构造函数写法

      class Promise{
        constructor(){
          this.callbacks  = []
        }
        
        then(onsuccess,onfail){
          // 储存一个对象里面有2中状态,一种是成功,一种是失败
          this.callbacks.push({
            resolve: onsuccess,
            reject: onfail
          })
          return this  //链式调用then  p1.then().then()....
        }
        
        resolve(result){
          this.complete('resolve',result)
        }
        
        reject(result){
          this.complete('reject',result)
        }
        
        complete(type,result){
          const callbackObj = this.callbacks.shift() //拿出数组第一个对象
          callbackObj[type](result)
        }
      }
      
      //调用这个Promise构造函数
      let p = new Promise()
      function fn() {
        console.log('fn1')
        setTimeout(()=>{p.resolve('data1')},1000)
        console.log('第一个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)
      //相当于数组里面存放2个对象
      // [{resolve:fn1,reject:undefined},{resolve:fn2,reject:undefined}]
      //then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
      
    2. Promise()知识点

相关文章

网友评论

      本文标题:ES 6(持续更新)

      本文链接:https://www.haomeiwen.com/subject/bnsstxtx.html