1. 程式人生 > >ES6 面向對象 promise

ES6 面向對象 promise

成功 ret resolv 可變 ise repeat 表示 timeout 個數

1. 變量/賦值

  • var 可以重復定義、不能限制修改、沒有塊級作用域
  • let 不能重復定義, 變量,塊級作用域
  • const 不能重復定義, 常量,塊級作用域

  • 結構賦值
    • 數組解構賦值
    • 對象解構賦值

2. 函數

  • 箭頭函數
 function(參數,參數){
  //  函數體
}
(參數, 參數)=>{
  // 函數體
}
  let arr=[12,5,88,34,32,19];

  /*arr.sort(function (n1, n2){
    return n1-n2;
  });*/
  arr.sort((n1, n2)=>{
    return n1-n2;
  });

  alert(arr);// 5,12,19,32,34,88
  // 1.有且僅有1個參數,()可以省去
  arr.sort((n1, n2)=>n1-n2);
  // 2.如果函數體只有一句話,而且是return,{}可以省
  /*let show=function (a){
        return a*3;
      };*/
      let show=a=>a*3;

      alert(show(13));

註意
箭頭函數有幾個使用註意點。

(1)函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。

(2)不可以當作構造函數,也就是說,不可以使用new命令,否則會拋出一個錯誤。

(3)不可以使用arguments對象,該對象在函數體內不存在。如果要用,可以用 rest 參數代替。

(4)不可以使用yield命令,因此箭頭函數不能用作 Generator 函數。

上面四點中,第一點尤其值得註意。this對象的指向是可變的,但是在箭頭函數中,它是固定的。

  • 函數參數的默認參數
  /*function show(a, b, c){
      b=b||5;
      c=c||12;

      console.log(a,b,c);
    }*/
  let show=(a, b=37, c=12)=>{
      console.log(a,b,c);
    }

  show(12, 37);// 12 37 12
  • 參數展開(剩余參數, 數組展開)
  1. ‘...‘的第一個用途: 接收剩余參數
    function show(a, b, ...名字)剩余參數必須在參數列表的最後
  2. ‘...‘的第二個用途:展開一個數組
 let show=(a, b, ...args) =>{
      console.log(a, b, args);
    }
    show(1,2,3,4,5,6,7,8) // 1 2  [3, 4, 5, 6, 7, 8]

 let arr = [1,2,3];
    arr.push(4,5,6);
    // alert(arr) // 1,2,3,4,5,6
    let arr1 = [1,2,3];
    let arr2 = [4,5,6];
    arr1.push(...arr2)
    alert(arr1) // 1,2,3,4,5,6


     function show1(...args){
      show2(...args);
    }

    function show2(a, b){
      alert(a+‘,‘+b);
    }

    show1(12, 5);
  • rest 參數

    rest 參數(形式為...變量名)
    獲取函數的多余參數,這樣就不需要使用arguments對象了。rest 參數搭配的變量是一個數組,該變量將多余的參數放入數組中。

  // arguments變量的寫法
  function sortNumbers() {
    return Array.prototype.slice.call(arguments).sort();
  }

  // rest參數的寫法
  const sortNumbers = (...numbers) => numbers.sort();
  // arguments對象不是數組,而是一個類似數組的對象。所以為了使用數組的方法,必須使用Array.prototype.slice.call先將其轉為數組。
  // rest 參數就不存在這個問題,它就是一個真正的數組,數組特有的方法都可以使用。下面是一個利用 rest 參數改寫數組push方法的例子。

  function push(array, ...items) {
      items.forEach(function(item) {
        array.push(item);
        console.log(item);
      });
    }

    var a = [];
    push(a, 1, 2, 3)  

3.數組/json

數組--5種

  • map 映射: 一個對一個
  • filter 過濾
  • forEach 遍歷
  • reduce 匯總
  • Array.from([array-like])=>[x,x,x]

    let aDiv=document.getElementsByTagName(‘div‘)獲取到的一個是一個array-like,可以使用from()方法轉為Array
    map

    let arr=[62, 55, 82, 37, 26];

    /*let arr2=arr.map(function (item){
      if(item>=60){
        return true;
      }else{
        return false;
      }
    });*/
    /*
    let arr2=arr.map(item=>{
        if(item>=60){
          return true;
        }else{
          return false;
        }
      });*/

    let arr2=arr.map(item=>item>=60);
    alert(arr2); //true,false,true,false,false

filter

  let arr=[12,5,88,37,21,91,17,24];

    let arr2=arr.filter(item=>item%2);

    alert(arr2);
   let arr=[12,5,88,37,21,91,17,24];

    let sum=0;
    arr.forEach(item=>{
      sum+=item;
    });

    alert(sum);

reduce

// 計算arr數組的和
    let arr=[12,5,88,37,21,91,17,24];

    let sum=arr.reduce((tmp,item,index)=>{
      console.log(tmp, item, index);

      return tmp+item;
    });

    console.log(sum);
    // 計算arr數組的平均值
    let ave=arr.reduce((tmp,item,index)=>{
      if(index<arr.length-1){
        return tmp+item;
      }else{    //最後一次叠代
        return (tmp+item)/arr.length;
      }
    });
    console.log(ave);

Array.from([array-like])=>[x,x,x]

    <!-- 用js改變div的北背景色 -->
  <style>
        div {width:200px; height:200px; background:#CCC; float:left; margin:10px;}
      </style>
      <script>
      window.onload=function (){
        let aDiv=document.getElementsByTagName(‘div‘);
        console.log(aDiv)
        Array.from(aDiv).forEach(div=>{
          div.style.background=‘yellow‘;
        });
      };
      </script>
    <body>
      <div class=""></div>
      <div class=""></div>
      <div class=""></div>
      <div class=""></div>
      <div class=""></div>
    </body>

json的兩個變化 -簡寫

  1. 簡寫: 名字和值一樣的,可以省
  2. function可以不寫
  let a=12;
  let b=5;

  let json={a, b};

  console.log(json);
/*let json={
      a: 12,
      b: 5,
      show: function (){
        alert(this.a+this.b);
      }
    };*/
    let json={
      a: 12,
      b: 5,
      show(){
        alert(this.a+this.b);
      }
    };

    json.show();

4.字符串

  • 模板字符串 可以輸入變量、可以隨意折行
  let json={name: ‘blue‘, age: 18};
  alert(`我叫:${json.name},我今年${json.age}歲`);
  • startsWith()
  • endsWith()
 if(sNum.startsWith(‘135‘)){
    alert(‘移動‘);
  }else{
    alert(‘聯通‘);
  }

  if(filename.endsWith(‘.txt‘)){
    alert(‘文本文件‘);
  }else{
    alert(‘圖片文件‘);
  }
  • 字符串的遍歷
    for ... of
  for (let codePoint of ‘foo‘) {
    console.log(codePoint)
  }
  // "f"
  // "o"
  // "o"
  • includes(), startsWith(), endsWith()

    傳統上,JavaScript 只有indexOf方法,可以用來確定一個字符串是否包含在另一個字符串中。ES6 又提供了三種新方法。

    • includes():返回布爾值,表示是否找到了參數字符串。
    • startsWith():返回布爾值,表示參數字符串是否在原字符串的頭部。
    • endsWith():返回布爾值,表示參數字符串是否在原字符串的尾部。
    let s = ‘Hello world!‘;
    
    s.startsWith(‘Hello‘) // true
    s.endsWith(‘!‘) // true
    s.includes(‘o‘) // true
    s.startsWith(‘world‘, 6) // true
    s.endsWith(‘Hello‘, 5) // true
    s.includes(‘Hello‘, 6) // false
  • repeat()

    repeat方法返回一個新字符串,表示將原字符串重復n次。

  ‘x‘.repeat(3) // "xxx"
  ‘hello‘.repeat(2) // "hellohello"
  ‘na‘.repeat(0) // ""

5.面向對象

  • class/constructor
  • extends/super

  • this
    • 普通函數: 根據調用者確定 this會變
    • 箭頭函數: 根據所在的環境 this恒定
    • bind 給函數定死一個this
    // 傳統的js對象
      function Person(name, age){
        this.name=name;
        this.age=age;
      }
    
      Person.prototype.showName=function (){
        alert(‘我叫‘+this.name);
      };
      Person.prototype.showAge=function (){
        alert(‘我‘+this.age+‘歲‘);
      };
    
      let p=new Person(‘blue‘, 18);
    
      p.showName();
      p.showAge();
    
      //------------------------------------------------
      function Worker(name, age, job){
        Person.call(this, name, age);
        this.job=job;
      }
    
      Worker.prototype=new Person();
      Worker.prototype.constructor=Worker;
      Worker.prototype.showJob=function (){
        alert(‘我是做:‘+this.job);
      };
    
      let w=new Worker(‘blue‘, 18, ‘打雜的‘);
    
      w.showName();
      w.showAge();
      w.showJob();
  • es6面向對象
 class Person{
      constructor(name, age){
        this.name=name;
        this.age=age;
      }

      showName(){
        alert(‘我叫‘+this.name);
      }
      showAge(){
        alert(‘我‘+this.age+‘歲‘);
      }
    }

    class Worker extends Person{
      constructor(name, age, job){
        //super-超類(父類)
        super(name, age);
        this.job=job;
      }

      showJob(){
        alert(‘我是做:‘+this.job);
      }
    }

    let w=new Worker(‘blue‘, 18, ‘打雜的‘);

    w.showName();
    w.showAge();
    w.showJob();
  • bind 改變this指向
  class Person{
      constructor(name, age){
        this.name=name;
        this.age=age;
      }

      showName(){
        alert(this);
        alert(‘我叫‘+this.name);
      }
      showAge(){
        alert(‘我‘+this.age+‘歲‘);
      }
    }




    let p=new Person(‘blue‘, 18);

    document.onclick=p.showName.bind(p);

6.Promise

  • Promise 解決異步操作
    • 同步-串行 簡單、方便
    • 異步並發 性能高、體驗好
  • Promise用法
let p=new Promise((resolve, reject)=>{
    resolve();

    reject();
  });

  p.then(()=>{}, ()=>{});
  • 單個
    let p=new Promise((resolve, reject)=>{
      //resolve       解決->成功
      //reject        拒絕->失敗

      $.ajax({
        url: ‘1.txt‘,
        dataType: ‘json‘,
        success(json){
          resolve(json);
        },
        error(err){
          reject(err);
        }
      });
    });

    p.then(json=>{
      alert(‘成功‘);
      console.log(json);
    }, err=>{
      alert(‘失敗‘);
    });
  • 多個 all([])
let p=new Promise((resolve, reject)=>{
      //resolve       解決->成功
      //reject        拒絕->失敗
      $.ajax({
        url: ‘1.txt‘,
        dataType: ‘json‘,
        success(json){
          resolve(json);
        },
        error(err){
          reject(err);
        }
      });
    });

    let p2=new Promise((resolve, reject)=>{
      //resolve       解決->成功
      //reject        拒絕->失敗
      $.ajax({
        url: ‘2.txt‘,
        dataType: ‘json‘,
        success(json){
          resolve(json);
        },
        error(err){
          reject(err);
        }
      });
    });

    let p3=new Promise((resolve, reject)=>{
      //resolve       解決->成功
      //reject        拒絕->失敗

      $.ajax({
        url: ‘3.txt‘,
        dataType: ‘json‘,
        success(json){
          resolve(json);
        },
        error(err){
          reject(err);
        }
      });
    });

    Promise.all([p, p2, p3]).then(arr=>{
      let [j1, a, j2]=arr;

      alert(‘成功‘);
      console.log(j1, a, j2);
    }, err=>{
      alert(‘失敗‘);
    });

1.Proimse有用——解除異步操作
2.Promise有局限——帶邏輯的異步操作麻煩

Promise.all(); 與:所有的都成功
Promise.race(); 或:只要有一個完成

  • generator-生成器
    • 能暫停
  • yield:
    1. 參數 function (a, b, c)
    2. 返回 return
      function *show(){
        alert(‘aaa‘);
    
        yield; // gne.next() 執行了yield的上部分,會停止下部分的執行。
        // 定時器中的gen.next()會執行下半部分
    
        alert(‘bbb‘);
      }
    
      let gen=show();
    
      gen.next();   //aaa
    
      setTimeout(function (){
        gen.next();   //bbb
      }, 5000);
     function *show(){
        alert(‘aaa‘);
    
        yield 55;
    
        alert(‘bbb‘);
    
        return 89;
      }
    
      let gen=show();
    
      let res1=gen.next();console.log(res1);    //{value: 55, done: false}
    
      let res2=gen.next();console.log(res2);    //{value: 89, done: true}

try catch捕捉async await 的錯誤

ES6 面向對象 promise