箭头函数
箭头函数的特点:
①: this 是静态的, this始终指向函数声明时所在作用域下的 this 的值, this的指向是父级函数的作用域
```javascript
// this 指向的是它所在的对象的父级
let obj = {
name: ‘tom’,
init:() => {
console.log(this);
}
}
```
②: 不能作为构造函数实例化对象
③: 不能使用 arguments 变量
④: 箭头函数的简写
<1>. 省略小括号,当形参有且只有一个的时候
<2>. 省略花括号, 当代码体只有一条语句的时候, 此时return必须省略,而且语句的执行结果就是函数的返回值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// ES6 允许使用[箭头] (=>)定义函数
// 声明一个函数
let fn = (a, b) => {
return a + b;
}
console.log(fn(1, 3));
// 1. this 是静态的 this 始终指向函数声明时所在作用域下的 this 的值
function getName() {
console.log(this.name + " getName() 普通函数");
}
// 全局作用域下声明的
let getName2 = () => {
console.log(this.name + ' getName2()箭头函数');
}
window.name = 'qfnu';
// getName();
// getName2();
const obj = {
name: 'QFNU'
}
getName.call(obj);
getName2.call(obj);
// 2. 不能作为构造函数实例化对象
// let Person = (name, age) => {
// this.name = name;
// this.age = age;
// }
// let me = new Person('tom', 18);
// 3.不能使用arguments变量
// let fn = () => {
// console.log(arguments);
// }
// fn(1, 2, 3);
// 4. 箭头函数可以简写
// <1>. 省略小括号, 当形参有且只有一个的时候
let add = n => {
return n + n;
}
// <2>. 省略花括号, 当代码体只有一条语句的时候, 此时return必须省略,而且语句的执行结构就是函数的返回值
let pow = n => n * n;
console.log(pow(9));
console.log(add(8));
</script>
</body>
</html>
**箭头函数的应用 **
箭头函数的this指向的是它声明时所在的作用域
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background: deeppink;
margin: 100px auto
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box = document.querySelector('.box');
box.addEventListener('click', function() {
// _this = this;
// setTimeout(function() {
// _this.style.backgroundColor = 'orange';
// }, 3000)
setTimeout(() => {
this.style.backgroundColor = "pink"
}, 3000)
})
</script>
</body>
</html>
需求 从数组中返回偶数的元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<script>
const arr = [1, 20, 33, 5, 6, 2];
const result = arr.filter(item => item % 2 === 0);
console.log(result);
const result1 = arr.filter(item => !(item % 2))
</script>
</body>
</html>