天天看点

箭头函数Arrow Function

最近在学习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

           

运行结果一一对应:

箭头函数Arrow Function

希望能对大家有所帮助。

参考:

https://zhuanlan.zhihu.com/p/34680105

https://www.liaoxuefeng.com/wiki/1022910821149312/1031549578462080