初探ECMAScript6

基礎變化前端

  1. String類型新增了三個方法,沒必要使用indexOf來判斷一個字符串是否在另外一個字符串內
    //String changes
    var a = "Hello world";
        var b = "Hello";
        var c = "world";
        function includes(source, dest) {
          return source.indexOf(dest) > -1;
        }
        function startsWith(source, dest) {
          return source.slice(0, dest.length) === dest;
        }
        function endsWith(source, dest) {
          return source.slice(source.length - dest.length, source.length) === dest;
        }
    
    var msg = "Hello world!";
    
        console.log("msg startsWith Hello: ", msg.startsWith("Hello"));       // true
        console.log("msg endsWith !: ", msg.endsWith("!"));             // true
        console.log("msg includes o:  ", msg.includes("o"));             // true
        
        console.log("msg startsWith o: ", msg.startsWith("o"));           // false
        console.log("msg endsWith world!: ", msg.endsWith("world!"));        // true
        console.log("msg includes x:  ", msg.includes("x"));             // false
  2. Object.is方法用來判斷兩個參數是否相等,與全等(===)相似只是在+0和-0上以及NaN與NaN的判斷上與全等不一樣
    console.log(+0 == -0);              // true
    console.log(+0 === -0);             // true
    console.log(Object.is(+0, -0));     // false
    
    console.log(NaN == NaN);            // false
    console.log(NaN === NaN);           // false
    console.log(Object.is(NaN, NaN));   // true
    
    console.log(5 == 5);                // true
    console.log(5 == "5");              // true
    console.log(5 === 5);               // true
    console.log(5 === "5");             // false
    console.log(Object.is(5, 5));       // true
    console.log(Object.is(5, "5"));     // false
  3. let聲明,let與var的做用相同,只是以let聲明的變量的做用域在當前的{}塊內
    function getValue(condition) {
    
        if (condition) {
            let value = "blue";
    
            // other code
    
            return value;
        } else {
    
            // value doesn't exist here
    
            return null;
        }
    
        // value doesn't exist here
    }
  4. const關鍵字用來聲明常量,常量一旦賦值就沒法改變,其餘的賦值表達式都會被忽略
  5. 解構賦值,引入解構賦值能夠方便的從複雜的對象中取得所需的屬性值
    var options = {
            repeat: true,
            save: false,
            rules: {
                custom: 10,
            }
        };
    
    // later
    
    var { repeat, save, rules: { custom }} = options;
    
    console.log(repeat);        // true
    console.log(save);          // false
    console.log(custom);        // 10

     

 

es6

  1. 類聲明語法,目前許多前端框架好比dojo、extJs使用輔助設計使得Javascript看起來支持「類」,基於以上目的ES6引入類體系;目前在Chrome使用class關鍵字必須使用嚴格模式
    //class declaration
    function PersonType(name) {
            this.name = name;
        }
        
        PersonType.prototype.sayName = function() {
            console.log(this.name);
        };
        
        let person = new PersonType("Nicholas");
        person.sayName();   // outputs "Nicholas"
        
        console.log(person instanceof PersonType);      // true
        console.log(person instanceof Object);      // true
    
    (function(){
    'use strict';
    class PersonClass {
            constructor(name) {
                this.name = name;
            }
            sayName() {
                console.log(this.name);
            }
        }
        
        let person = new PersonClass("Nicholas");
        person.sayName();   // outputs "Nicholas"
        
        console.log(person instanceof PersonClass);     
        console.log(person instanceof Object);  
    })()
  2. 屬性訪問器,經過使用get和set關鍵字來聲明屬性(Attribute),在ES5中須要藉助Object.defineProperty來聲明屬性訪問器
    //Accessor Properties
    (function(){
          'use strict';
          class PersonClass {
            constructor(name) {
                this.name = name;
            }
            get Name(){
              return this.name;
            }
            set Name(value){
              this.name = value;
            }
          }
        
          let person = new PersonClass("Nicholas");
          console.log('person.Name: ', person.Name)   // outputs "Nicholas"
        })()
  3. 靜態成員,ES5或者以前的代碼經過在構造函數中直接定義屬性來模擬靜態成員;ES6則只須要在方法名前面加上static關鍵字
    //ES5
    function PersonType(name) {
        this.name = name;
    }
    
    // static method
    PersonType.create = function(name) {
        return new PersonType(name);
    };
    
    // instance method
    PersonType.prototype.sayName = function() {
        console.log(this.name);
    };
    
    var person = PersonType.create("Nicholas");
    
    //ES6
    //Static Members
    (function(){
          'use strict';
          class PersonClass {
            constructor(name) {
              this.name = name;
            }
              
            sayName() {
              console.log(this.name);
            }
            
            static create(name) {
              return new PersonClass(name);
            }
          }
          
          let person = PersonClass.create("Nicholas");
          console.log(person);
        })()
  4. 繼承,ES5中須要藉助prototype屬性而ES6中引入extends關鍵字來實現繼承
    //Handling Inheritance
    (function(){
          'use strict';
          class PersonClass {
            constructor(name) {
              this.name = name;
            }
          }
          
          class Developer extends PersonClass {
            constructor(name, lang) {
              super(name);
              this.language = lang;
            }
          }
          
          var developer = new Developer('coder', 'Javascript');
          console.log("developer.name: ", developer.name);
          console.log("developer.language: ", developer.language);
        })()

     

模塊機制json

  當前關於JS的模塊化已有兩個重要的規範CommonJs和AMD,但畢竟不是原生的模塊化,因此ES6中引入模塊化機制,使用export和import來聲明暴露的變量和引入須要使用的變量promise

  

 

Iterator和Generator前端框架

  Iterator擁有一個next方法,該方法返回一個對象,該對象擁有value屬性表明這次next函數的值、done屬性表示是否擁有繼續擁有可返回的值;done爲true時表明沒有多餘的值能夠返回此時value爲undefined;Generator函數使用特殊的聲明方式,generator函數返回一個iterator對象,在generator函數內部的yield關鍵字聲明瞭next方法的值app

//Iterator & Generator
// generator
    function *createIterator() {
        yield 1;
        yield 2;
        yield 3;
    }
    
    // generators are called like regular functions but return an iterator
    var iterator = createIterator();
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());

 

Promise框架

  ES6引入原生的Promise對象,Promise構造函數接受一個方法做爲參數,該方法中能夠調用resolve和reject方法,分別進入fulfill狀態和fail狀態ecmascript

// Promise
var getJSON = function(url) {
  var promise = new Promise(function(resolve, reject){
    var client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.send();

    function handler() {
      if (this.readyState !== 4) {
        return;
      }      
      if (this.status === 200) {
      debugger;
        resolve(this.responseText);
      } else {
        reject(new Error(this.statusText));
      }
    };
  });

  return promise;
};

getJSON("https://gis.lmi.is/arcgis/rest/services/GP_service/geocode_thjonusta_single/GeocodeServer?f=json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('Error: ', error);
});

 

Proxy模塊化

  顧名思義用來做爲一個對象或函數的代理。Proxy構造函數接受兩個參數:target用來被封裝的對象或函數、handler擁有一系列方法,重寫這些方法以便當調用這些操做時會進入重寫的方法中函數

•handler.getPrototypeOf
•handler.setPrototypeOf
•handler.isExtensible
•handler.preventExtensions
•handler.getOwnPropertyDescriptor
•handler.defineProperty
•handler.has
•handler.get
•handler.set
•handler.deleteProperty
•handler.enumerate
•handler.ownKeys
•handler.apply
•handler.construct
handler.getPrototypeOf
handler.setPrototypeOf
handler.isExtensible
handler.preventExtensions
handler.getOwnPropertyDescriptor
handler.defineProperty
handler.has
handler.get
handler.set
handler.deleteProperty
handler.enumerate
handler.ownKeys
handler.apply
handler.construct

 

參考資料:

Understanding ECMAScript 6

ECMAScript 6 入門

相關文章
相關標籤/搜索