[ES6] 06. Arrow Function =>

ES6 arrow function is somehow like CoffeeScirpt.ide

CoffeeScript:函數

 //function                     call
coffee = ->                    coffee()
coffee=(message) ->            coffee("Yo"), coffee "Yo"
coffee=(message, other) ->     coffee("Yo", 2), coffee "Yo", 2

 

Now we rewrite a ES5 function to ES6 function:ui

ES5:this

var greeting = function(message, name){
    return  message + name;
}

ES6:spa

First thing in ES6, we can remove the function keyword and add => on the right side of the params:code

var greeting = (message, name) => {
   return message + name ;  
}

Second, we can remove 'return' and {};對象

var greeting = (message, name) => message + name

 

Example 1:blog

var f = () => 5; 
// 等同於
var f = function (){ return 5 };

Example 2:ip

 

 
 
//ES6
var msg = message => "Hello Es6"//ES5
var msg = function(message){
 return "Hello Es6";   
}

Example 3:ci

// 正常函數寫法
[1,2,3].map(function (x) {
  return x * x;
});

// 箭頭函數寫法
[1,2,3].map(x => x * x);

Example 4:

// 正常函數寫法
var result = values.sort(function(a, b) {
    return a - b;
});

// 箭頭函數寫法
var result = value.sort((a,b)=> a- b)

 

 

=> function helps to sovle the context problem:


 

//ES5

var deliveryBoy = {
    name: "John",

    receive: function(){
        var that = this;
        this.handleMessage("Hello", function(message){
            //Here we have a very amazing handle function
            //which combine the name and message
            console.log(message + ' '+that.name);
        });
    },

    handleMessage: function(message, handler){
        handler(message);
    }

}

deliveryBoy.receive();

In the code, we see:

console.log(message + ' '+that.name);

We use var that = this; and that.name to refer to "John". It looks quite confusing.

 

Arrow function helps us out of this:


 

var deliveryBoy = {
    name: "John",

    receive: function(){this.handleMessage("Hello", message => console.log(message + ' '+this.name));
    },

    handleMessage: function(message, handler){
        handler(message);
    }

}

deliveryBoy.receive();

Inside the code, we still use this.name to refer "John". This is because, => refer to the deliveryBoy object.

 

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

  • 函數體內的this對象,綁定定義時所在的對象,而不是使用時所在的對象。
  • 不能夠看成構造函數,也就是說,不可使用new命令,不然會拋出一個錯誤。
  • 不可使用arguments對象,該對象在函數體內不存在。
相關文章
相關標籤/搜索