Skip to content

From ES5 To ES6

flyw edited this page Jul 12, 2018 · 1 revision

箭头函数

箭头函数使我们的代码更简洁,并简化了函数作用域this关键字。 它们是单行迷你函数。 通过使用箭头函数,我们避免必须键入function 关键字,return关键字(它隐含在箭头函数中)和 大括号。

  1. 多参数的基本语法

    // ES5
    var multiplyES5 = function(x, y) {
      return x * y;
    };
    
    // ES6
    const multiplyES6 = (x, y) => { return x * y };
  2. 一个参数的基本语法

    //ES5
    var phraseSplitterEs5 = function phraseSplitter(phrase) {
      return phrase.split(' ');
    };
    
    //ES6
    const phraseSplitterEs6 = phrase => phrase.split(" ");
    
    console.log(phraseSplitterEs6("ES6 Awesomeness"));  // ["ES6", "Awesomeness"]
  3. 没有参数

    var docLogEs5 = function docLog() {
        console.log(document);
    };
    
    //ES6
    var docLogEs6 = () => { console.log(document); };
    docLogEs6(); // #document... <html> ….
  4. 对象语法

    箭头函数(如函数表达式)可用于返回对象。

    //ES5
    var setNameIdsEs5 = function setNameIds(id, name) {
      return {
        id: id,
        name: name
      };
    };
    
    // ES6
    var setNameIdsEs6 = (id, name) => ({ 
        id: id, 
        name: name 
    });
    
    console.log(setNameIdsEs6 (4, "Kyle"));   // Object {id: 4, name: "Kyle"}
  5. 承诺(Promises) 和 回调(Callbacks)

    // ES5
    aAsync().then(function() { returnbAsync(); })
            .then(function() { returncAsync(); })
            .done(function() { finish(); });
    // ES6
    aAsync().then(() => bAsync())
            .then(() => cAsync())
            .done(() => finish);

    使用带有promise / callbacks的箭头函数的另一个好处是它减少了对this关键字的混淆。 在具有多个嵌套函数的代码中,可能难以跟踪并记住绑定正确的此上下文。 在ES5中,您可以使用.bind方法(这很慢)或使用var self = this;创建闭包的变通方法。

    因为箭头函数允许您在函数内保留调用者的范围,所以您不需要创建self = this closures或使用bind。

    // ES5
    API.prototype.get = function(resource) {
    
      var self = this;
    
      return new Promise(function(resolve, reject) {
        http.get(self.uri + resource, function(data) {
          resolve(data);
        });
      });
    };
    // ES6
    API.prototype.get = function(resource) {
    
      return new Promise((resolve, reject) => {
        http.get(this.uri + resource, function(data) {
          resolve(data);
        });
      });
    };

Clone this wiki locally