1.箭头函数
作用:简化函数
// 普通函数
const fn1 = function () {
console.log(111);
}
// 箭头函数
const fn2 = () => {
console.log(222);
}
语法:
- 有参数
const fn3 = (x) => {
console.log(x);
}
fn3(333)
- 只有一个形参时,可省略小括号
const fn4 = x => {
console.log(x);
}
fn4(444)
- 只有一行代码时,可省略大括号
const fn5 = x => console.log(x);
fn5(555)
- 只有一行代码时,有返回值,不用写return
const fn6 = x => x + x;
console.log(fn6(333));
- 可以直接返回一个对象
const fn = (uname) => ({ uname: uname })
console.log(fn('555'));
应用: 利用箭头函数求和
const getSum = (...arr) => {
let sum = 0
for (let i = 0; i < arr.length; i++) {
sum += i
}
return sum
}
console.log(getSum(1, 2, 3, 4, 5));
2.箭头函数的this
- 在箭头函数之前,每一个函数的this取决于这个函数是如何被调用的
// 在上一层script中找到的this指向window
const fun1 = () => {
console.log(this);
}
fun1() // window
- 箭头函数不会创建自己的this,只会沿用作用域链的上一层this
// 函数ing在外层对象obj1中没有找到this(obj1是对象,函数里面才有this)
const obj1 = {
uname: 'Tom',
ing: () => {
console.log(this);
}
}
obj1.ing() // window
// 函数nei在他上一层,函数wai里面找到了this(函数里面才有this)
const obj2 = {
uname: 'Tom',
wai: function () {
let i = 1
console.log(this);
const nei = () => {
console.log(this);
}
ing()
}
}
obj2.wai() // obj
// 同样,如果想使用this,不推荐使用箭头函数
3.改变this指向
call()
- 作用
-
- 调用函数
- 改变this指向
- 第一个参数是需要指向的对象,后面的参数是函数形参依次对应的实参
const obj = {
name: 'Tom'
}
function fn(x, y) {
console.log(this); // {name: 'Tom'}
console.log(x + y); // 3
}
fn.call(obj, 1, 2)
apply()
-
apply()也可以调用函数和改变this指向
-
apply()与call()相比,传入的实参必须是以数组形式
const obj = {
name: 'Tom'
}
function fn(x, y) {
console.log(this); // {name: 'Tom'}
console.log(x + y); // 3
}
fn.apply(obj, [1, 2])
bind()
- bind()也可以改变this指向,但不会调用函数
- bind()返回值是this指向更改过的函数(原函数this指向不变)
let that
const obj = {
name: 'Tom'
}
function fn(x, y) {
that = this
}
fn()
// 原函数指向 window
console.log(that); // window
const newFunction = fn.bind(obj)
newFunction()
// 新函数指向 obj
console.log(that); // {name: 'Tom'}
fn()
// 原函数this指向不变,依旧指向 window
console.log(that); // window