介绍
使用箭头函数可以更方便的书写函数体,它的作用只在于为匿名函数提供更简洁得写法
- 特点:
- 在箭头函数中没有this指针
- 在箭头函数中没有arguments动态参数,但是有…args剩余参数
目录
文章目录
基本使用
函数表达式
const fn = function(){
console.log(123);
};
箭头函数基本语法
const fn = () => {
console.log(123);
};
fn();
传入参数:
单个参数
单个参数-基础写法
const fn = (x) => {
console.log(x);
};
fn(1);
单个参数-精简写法
单个参数可以省略括号
const fn = x => {
console.log(x);
};
fn(1);
单个参数-将参数以对象形式返回
函数中只有单行语句时可以省略大括号{}
下面代码中并未省略大括号但是因为要求返回得事对象的形式故而是双重大括号 而这样写是有问题的 因此将外面大括号改成小括号即可
const fn = uname => ({name: uname});
下面代码其实已经省略大括号 只是我们要求返回的是一个对象 故而又加上了大括号
const fn = uname => {name: uname};
多个参数
- 在箭头函数中可以使用…args,无法使用arguments关键字
// 1. 利用箭头函数来求和
const getSum = (...arr) => {
let sum = 0
for (let i = 0; i < arr.length; i++) {
sum += arr[i]
}
return sum
}
const result = getSum(2, 3, 4)
console.log(result) // 9
箭头函数this指向
- 在传统函数中谁调用了函数,this就指向谁
- 在箭头函数中this指向它所在作用域链的上一层作用域
- 为DOM事件添加监听时不建议使用箭头函数(不方便)//合适的地方做合适的事
下面将展示各种情况下this指向
↓↓↓各种情况下this指向↓↓↓
普通函数
// 以前this的指向: 谁调用的这个函数,this 就指向谁
console.log(this) // window
// 普通函数
function fn() {
console.log(this) // window
}
window.fn()
对象方法
// 对象方法里面的this
const obj = {
name: 'andy',
sayHi: function () {
console.log(this) // obj
}
}
obj.sayHi()
箭头函数
// 2. 箭头函数的this 是上一层作用域的this 指向
const fn = () => {
console.log(this) // window
}
fn()
对象方法箭头函数
箭头函数取上一作用域调用对象,指向obj,而obj默认通过window.obj调用,因此指向window
// 对象方法箭头函数 this
const obj = {
uname: 'pink老师',
sayHi: () => {
console.log(this) // this 指向谁? window
}
}
obj.sayHi()
对象中传统函数内调用箭头函数
const obj = {
uname: 'pink老师',
sayHi: function () {
console.log(this) // obj
let i = 10
const count = () => {
console.log(this) // obj
}
count()
}
}
obj.sayHi()