ES6 一些新特性的總結


一、箭頭函數

     ES6中新增了一個箭頭函數   ()=>,箭頭函數通俗點講就是匿名函數。箭頭函數還有不同點在於改變函數中this,和js中的.bind  的方法差不多,繼承后指向的不是最新的函數,還是之前的那個原型對象。

      

二、類的支持

      ES6中添加了對類的支持,引入了class關鍵字。JS本身就是面向對象,ES6中提供的類實際上只是JS原型模式包裝。現在有了class,對象的創建,繼承更直觀,父類方法的調用,實例化,靜態方法和構造函數更加形象化。

      

   //類的定義
   
   class Animal {
        constructor(name) {
            this.name =name;
      }
    
  //實例方法

   sayName (){
        console.log ('My name is' + this.name);

      }

   }

//類的繼承

 class Product  extends Animal{

      constructor(name) {
           //直接調用父類構造器進行初始化
       super(name);
   }

    progrom() {
    console.log ('I'm coding....');
   }
 }

  //測試我們的類
var animal=new Animal('dummy'),
wayou=new Product('wayou');
animal.sayName();//輸出 ‘My name is dummy’
wayou.sayName();//輸出 ‘My name is wayou’
wayou.Product();//輸出 ‘I'm coding...’

 

 三、增強的對象字面量

    實現繼承,可以直接在對象字面量里面定義原型,不用再用function 關鍵字。

   

//  通過對象字面量創建對象

   var  human = {
          breathe  () {
             console.log ('breathing...');
     }
};


  var worker = {
      __proto__:human, //設置此對象的原型為human,相當於繼承human
   
    company:‘freeLancer’,
    work() {
       console.log ('working...');
    
       }
  };

 human.breathe();//輸出 ‘breathing...’
 //調用繼承來的breathe方法
 worker.breathe();//輸出 ‘breathing...’

 

四、利用‘ ‘ 反引號創建字符串,這其中可以包括${vraible}

      

 //產生一個隨機數
 
   var num =Math.random();

 // 講這個數輸出到console

   console.log (‘ your num is ${num}‘);

 

五、解構

   自動解析數組或對象中的值,不用以對象的方式返回。

   

1、var [x,y] = getVal(),//利用函數返回值進行解構
    [name,,age]=['wayou','male','secrect'];// 利用數組進行解構

   function getVal () {

       return [1,2];
   }


  console.log ('x:' +x+' ,y:'+y);//輸出:x:1, y:2
  console.log('name:'+name+', age:'+age);//輸出: name:wayou, age:secrect 

  

  六、可以定義默認的參數

      

 function sayHello2(name='dude'){
    console.log(`Hello ${name}`);
}

sayHello2();//輸出:Hello dude
sayHello2('Wayou');//輸出:Hello Wayou

七、Math  新增了一些API

   

八、Promises

    

//創建promise
var promise = new Promise(function(resolve, reject) {
    // 進行一些異步或耗時操作
    if ( /*如果成功 */ ) {
        resolve("Stuff worked!");
    } else {
        reject(Error("It broke"));
    }
});
//綁定處理程序
promise.then(function(result) {
    //promise成功的話會執行這里
    console.log(result); // "Stuff worked!"
}, function(err) {
    //promise失敗會執行這里
    console.log(err); // Error: "It broke"
});

   ES6  里面Promise 可以用來避免異步操作函數里的嵌套回調(callback hell) 問題,'.then().then()';

   適用於 ajax網絡請求、讀取localstorage等操作。

 

   常規的回調嵌套:

   

Parse.User.logIn("user","pass", {
 success:function(user) {
  query.find({
   success:function(results) {
    results[0].save({ key: value }, {
     success:function(result) {
      // the object was saved.
     },
     error:function(result, error) {
      // An error occurred.
     }
    });
   },
   error:function(error) {
    // An error occurred.
   }
  });
 },
 error:function(user, error) {
  // An error occurred.
 }
});

    Promise 的實現過程:

    

Parse.User.logIn("user","pass").then(function(user) {
 returnquery.find();
}).then(function(results) {
 returnresults[0].save({ key: value });
}).then(function(result) {
 // the object was saved.
},function(error) {
 // there was some error.
});

   直接到錯誤的地方就不在繼續執行.then,而是跳出執行error狀態下的function。

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM