ES6 Object-oriented Promise

Source: Internet
Author: User
Tags try catch

1. Variable/Assignment
    • var can be defined repeatedly, cannot limit modifications, and does not have block-level scopes
    • Let cannot repeat definitions, variables, block-level scopes
    • Const cannot be defined repeatedly, constants, block-level scopes

    • Structure Assignment
      • Array Deconstruction Assignment
      • Object Deconstruction Assignment
2. Functions
    • Arrow functions
 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));

Attention
The arrow functions have several points of note to use.

(1) The This object in the body of the function is the object that the definition is in, not the object in which it is used.

(2) cannot be used as a constructor, that is, you cannot use the new command, or you will throw an error.

(3) The arguments object cannot be used, and the object does not exist in the function body. If you want to use it, you can use the rest parameter instead.

(4) The yield command cannot be used, so the arrow function cannot be used as a Generator function.

Of the above four points, the 1th is particularly noteworthy. The pointer to this object is mutable, but in the arrow function it is fixed.

    • Default parameters for function parameters
  /*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
    • Parameter expansion (remaining parameters, array expansion)
    1. The first purpose of ' ... ': receive the remaining parameters
      function show(a, b, ...名字)剩余参数必须在参数列表的最后
    2. The second purpose of ' ... ': expand an array
 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 parameters

      Rest parameters (in the form ...) Variable name)
      Get the extra arguments to the function so that you don't need to use the arguments object. The variable that is paired with the rest parameter is an array that puts the extra arguments into the array.

  // 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. Array/json

Array of--5

    • Map map: one for a
    • Filter filters
    • ForEach traversal
    • Reduce rollup
    • Array.from ([array-like]) =>[x,x,x]

      Let Adiv=document.getelementsbytagname (' div ') gets to a array-like that can be converted to an array using the From () method
      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>
Two changes to JSON-shorthand
    1. Shorthand: The same name and value, you can save
    2. function can not write
  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. String
    • Template strings can be entered into variables, can be arbitrarily folded line
  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(‘图片文件‘);  }
    • Traversal of strings
      For ... of
  for (let codePoint of ‘foo‘) {    console.log(codePoint)  }  // "f"  // "o"  // "o"
    • Includes (), StartsWith (), EndsWith ()

      Traditionally, JavaScript has only the IndexOf method, which can be used to determine whether a string is contained in another string. ES6 also offers three new methods.

      • Includes (): Returns a Boolean value that indicates whether the parameter string was found.
      • StartsWith (): Returns a Boolean value that indicates whether the parameter string is in the header of the original string.
      • EndsWith (): Returns a Boolean value that indicates whether the parameter string is at the end of the original string.
      let s = ‘Hello world!‘;s.startsWith(‘Hello‘) // trues.endsWith(‘!‘) // trues.includes(‘o‘) // trues.startsWith(‘world‘, 6) // trues.endsWith(‘Hello‘, 5) // trues.includes(‘Hello‘, 6) // false
    • Repeat ()

      The Repeat method returns a new string indicating that the original string is repeated n times.

  ‘x‘.repeat(3) // "xxx"  ‘hello‘.repeat(2) // "hellohello"  ‘na‘.repeat(0) // ""
5. Object-oriented
    • class/constructor
    • Extends/super

    • This
      • normal function: Based on caller's confirmation this will change
      • Arrow Header function: According to the environment in which this constant
      • bind to the function to kill a This
       //Traditional JS object function person (nam    E, age) {this.name=name;  This.age=age;  } person.prototype.showname=function () {alert (' I call ' +this.name ');  };  Person.prototype.showage=function () {alert (' I ' +this.age+ ' years ');  };  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 (' I am doing: ' +this.job);  };  Let W=new Worker (' Blue ', 18, ' handyman ');  W.showname ();  W.showage ();
       W.showjob ();  
    • Es6 Object-oriented
 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 change this point
  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 Resolving asynchronous operations
      • Synchronization-Simple and convenient serial
      • High asynchronous concurrency performance, good experience
    • Promise Usage
let p=new Promise((resolve, reject)=>{    resolve();    reject();  });  p.then(()=>{}, ()=>{});
    • Single
    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(‘失败‘);    });
    • multiple all ([])
Let P=new Promise ((Resolve, reject) =>{//resolve resolution, Success//reject deny, fail $.ajax ({        URL: ' 1.txt ', DataType: ' JSON ', success (JSON) {resolve (JSON);        }, error (ERR) {reject (err);    }      });    });        Let P2=new Promise ((Resolve, reject) =>{//resolve resolution, Success//reject deny, fail $.ajax ({        URL: ' 2.txt ', DataType: ' JSON ', success (JSON) {resolve (JSON);        }, error (ERR) {reject (err);    }      });    });        Let P3=new Promise ((Resolve, reject) =>{//resolve resolution, Success//reject deny, fail $.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 (' success ');    Console.log (J1, A, J2);   }, err=>{   Alert (' failure '); });

1.Proimse Useful--Cancel asynchronous operation
2.Promise Limited--logical asynchronous Operation trouble

Promise.all (); And: All of them are successful
Promise.race (); Or: As long as there is a complete

    • generator-Generator
      • Can pause
    • Yield
      1. Parameter function (A, B, c)
      2. Back to 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 catches async await error

ES6 Object-oriented Promise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.