Vue ES6箭頭函數使用總結

  • 2019 年 12 月 20 日
  • 筆記

Vue ES6箭頭函數使用總結

箭頭函數

ES6允許使用「箭頭」(=>)定義函數:

函數不帶參數

定義方法:函數名稱 = () => 函數體

let func = () => 1

等同於

function func() {

return 1;

}

函數只帶一個參數

定義方法:

函數名稱 = 參數 => 函數體

或者

函數名稱 = (參數) => 函數體

let func = state => state.count

等同於

function func(state) {

return state.count;

}

函數帶多個參數

定義方法:函數名稱 = (參數1,參數2,…,參數N) =>函數體

let arg2 = 1

let func = (state, arg2) => state.count + arg2

等同於

function func(state,arg2) {

return state.count + arg2;

}

函數體包含多條語句

let author = {

name: "授客",

age: 30,

viewName: () => {

console.log("author name"); // 輸出undefined

// 當前this指向了定義時所在的對象

console.log(this.name); // 輸出undefined,並沒有得到"授客"

}

};

author.viewName();

注意

函數體內的this對象,就是定義時所在的對象,而不是使用它時所在的對象