最近在學習vue的時候遇到了關于箭頭函數的使用,是以學習後在這裡一起分享一下。
箭頭函數:ES6标準新增的一種新的函數(Arrow Function),可以把它們看作是能附加在單擊事件或滑鼠事件上的一次性函數,箭頭函數相當于匿名函數,并且簡化了函數定義
缺點:
不能用來聲明一個函數,也不能夠通過 new 關鍵字建立對象執行個體
eg:
x => x*x
等價于:
function (x) {
return x * x;
}
先說一下箭頭函數的文法:
左邊:參數部分
1.如果沒有參數,直接括号,并且不可以省略
() => 8+9;
2.隻有一個參數:
x => x*x;
3.兩個參數
(x,y) => x*y
4.可變參數
(x, y, ...rest) => {
var i, sum = x + y;
for (i=0; i<rest.length; i++) {
sum += rest[i];
}
return sum;
}
中間:=> 固定不變
右邊:
1.函數體部分隻有一句表達式并且需要傳回這個表達式的值時,可以省略大括号
x => x*x;
2.包含多條語句時大括号和return都不能省略
x => {
if(x>0){
return x*x;
}else{
return x+x;
}
}
3.當傳回的是一個對象的時候,右邊最外層要加大括号包裹
(x,y) => ({a:x*y,b:x+y})
最後便是箭頭函數中this的用法了:
對于箭頭函數來說,它沒有自己的 this ,它的 this 将始終指向讓它生效的對象,即它的外部調用者(箭頭函數内部的this是詞法作用域,由上下文确定)
const test4 = {
arrowFunc: () => { console.log(this) },
normalFunc: function () { console.log(this) }
}
// test4.arrowFunc 在全局對象 window 下生效,指向 window
test4.arrowFunc() // window
// 普通方式聲明的函數 this 指向持有這個函數的對象,即 test4
test4.normalFunc() // obj1
const test5 = {
arrowFunc: function () {
setTimeout(() => { console.log(this) }, 0)
},
normalFunc: function () {
setTimeout(function () { console.log(this) }, 0)
}
}
// arrowFunc 中的箭頭函數在 test5 下生效,指向 test5
test5.arrowFunc() // test5
// normalFunc 中的匿名函數的 this 始終指向 window
test5.normalFunc() // window
var that = this;這種用法就廢棄了。
完整源碼測試:
import Vue from 'vue'
import store from './store'
import vuex_test from './vuex_test.vue'
const test1 = x => x*x
console.log('test1---'+test1(10))
const test2 = () => 8*9
console.log('test2---'+test2())
const test3 = (x,y) => ({a:x*y,b:x+y})
console.log('test3---'+JSON.stringify(test3(1,2)))
const test4 = {
arrowFunc: () => { console.log(this) },
normalFunc: function () { console.log(this) }
}
// test4.arrowFunc 在全局對象 window 下生效,指向 window
test4.arrowFunc() // window
// 普通方式聲明的函數 this 指向持有這個函數的對象,即 test4
test4.normalFunc() // obj1
const test5 = {
arrowFunc: function () {
setTimeout(() => { console.log(this) }, 0)
},
normalFunc: function () {
setTimeout(function () { console.log(this) }, 0)
}
}
// arrowFunc 中的箭頭函數在 test5 下生效,指向 test5
test5.arrowFunc() // test5
// normalFunc 中的匿名函數的 this 始終指向 window
test5.normalFunc() // window
運作結果一一對應:
希望能對大家有所幫助。
參考:
https://zhuanlan.zhihu.com/p/34680105
https://www.liaoxuefeng.com/wiki/1022910821149312/1031549578462080