傳統我們在寫javascript時都是用function來建立函式,ES6則可使用「=>」來建立函式!
1.直接回傳結果:(參數)=>(回傳值)
//傳統寫法
let add = function(pNumber1, pNumber2){
return pNumber1 + pNumber2;
}
//箭頭函式寫法
let add = (pNumber1, pNumber2) => (pNumber1+pNumber2);
//範例
let myFunc=() => (5);
let myResult = myFunc();
console.log(myResult); //5
2.撰寫函式內部程式:(參數)=>{函式內部程式}
//傳統寫法
let add = function(pNumber1, pNumber2){
return pNumber1 + pNumber2;
}
//箭頭函式寫法
let add = (pNumber1, pNumber2) => {
return pNumber1 + pNumber2;
};
//範例
let myFunc = (pNumber1, pNumber2) => {
console.log(pNumber1+pNumber2);
}
myFunc(5,6); //11!!
3.匿名函式
//傳統寫法
setTimeout(function(){
console.log("等了1秒..");
},1000);
//箭頭函式寫法
setTimeout(() => {
console.log("等了1秒..");
},1000);
4.指定參數的預設值:(param1=預設值, param2=預設值)
//傳統寫法
function myFunc(pMsg){
if(pMsg == undefined){
pMsg = "I am Batman!";
}
console.log(pMsg);
}
//ES6寫法
function myFunc(pMsg="I am Batman!"){
console.log(pMsg);
}
//箭頭函式寫法
let myFunc=(pMsg="I am Batman!") => {
console.log(pMsg);
}
//範例
myFunc("Hello Batman!")//Hello Batman!
myFunc()//I am Batman!