ES6允许使用[箭头] (=>)定义函数
箭头函数的特点:
1.this是静态的。this始终指向函数声明时,所在作用域下的this值
2.不能作为构造实例化对象
3.不能使用arguments变量
4.箭头函数的简写
<!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 = function(){
// }
// let fn = (a,b) =>{
// return a + b;
// }
// //调用函数
// let result = fn(1,2);
// console.log(result)
//1.this是静态的。this始终指向函数声明时,所在作用域下的this值
function getName(){
console.log(this.name)
}
let getName2 = () =>{
console.log(this.name)
}
//设置windows对象的name属性
window.name = '凡凡'
const school = {
name: 'FANFAN'
}
//直接调用
// getName();
// getName2();
//call 方法调用
//getName.call(school);
//getName2.call(school);
//2.不能作为构造实例化对象
// let Person = (name,age) => {
// this.name = name;
// this.age = age;
// }
// let me = new Person('xiao',30);
// console.log(me);
//3.不能使用arguments变量
// let fn = () =>{
// console.log(arguments);
// }
// fn(1,2,3);
//4箭头函数的简写
//省略小括号,当形参有且只有一个的时候
let add = n => {
return n+n;
}
console.log(add(9));
//省略花括号,当代码体只有一条语句的时候,此时return必须省略
// let pow = (n) =>{
// return n*n;
// }
let pow = n => n*n
console.log(pow(9))
</script>
</body>
</html>
箭头函数的小案例:
箭头函数不适合与this无关的回调,定时器,数组的方法回调
箭头函数不适合与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>
div {
width: 200px;
height: 200px;
background: #58a;
}
</style>
</head>
<body>
<div id="ad">
</div>
<script>
//需求1 点击div 2s后颜色变成粉色
//获取元素
let ad = document.getElementById('ad')
//绑定事件
ad.addEventListener("click",function(){
//保存this的值
let _this = this;
//定时器
setTimeout(() => {
//修改背景颜色 this
//console.log(this);
//_this.style.background = 'pink';
this.style.background = 'pink';
},2000);
})
//需求2 从数组中返回偶数的元素
const arr = [1,6,9,10,100,25,27,48,28]
// const result = arr.filter(function(item){
// if(item % 2 == 0){
// return true;
// }else{
// return false;
// }
// });
// console.log(result);
// const result = arr.filter(item => {
// if(item % 2 == 0){
// return true;
// }else{
// return false;
// }
// });
const result = arr.filter(item => item % 2 === 0);
console.log(result);
//箭头函数不适合与this无关的回调,定时器,数组的方法回调
//箭头函数不适合与this有关的回调,事件回调,对象的方法
</script>
</body>
</html>