1. 箭头函数
let fn = function(){
}
//改写成箭头函数
let fn = ()=>{}
//调用
fn();//调用方法一样
this
是静态的,this
始终指向函数声明时所在作用域下的this
的值
function getName(){
console.log(this.name);
}
let getName2 = ()=> {
//在全局作用域下声明,this指向window,且不会再改变
console.log(this.name);
}
//设置window对象的name属性
window.name = "尚硅谷";
const school = {
name:"ATGUIGU"
}
//直接调用
getName(); //输出"尚硅谷"
getName2(); //输出"尚硅谷"
//使用call方法(改变函数内部this的值)
getName.call(school); //输出"ATGUIGU"
getName2.call(school); //输出"尚硅谷"
- 注意: 重点关注最后一行代码,输出依然不变,也就是
this
值没有变
- 不能作为构造函数实例化对象
let Person = (name,age) =>{
this.name = name;
this.age = age;
}
let me = new Person("xiao",30);
console.log(me); //报错:Person is not a constructor
let fn = ()=>{
console.log(arguements);
}
fn(1,2,3); //报错:arguements is not defined
- 箭头函数的简写
- 省略小括号:当形式参数有且仅有一个时
let add = n =>{return n+n};
- 省略花括号:当函数体只有一条语句时,此时
return
必须省略
let add = n => n+n;
2. 箭头函数-案例
案例1 -点击div,2s后变色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 100px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div id="ad"></div>
<script>
let ad = document.getElementById("ad");
ad.addEventListener("click",function(){
setTimeout(function(){
//修改背景色 使用this
this.style.background = "pink"; //报错,background是undefined
},2000);
});
</script>
</body>
</html>
let ad = document.getElementById("ad");
ad.addEventListener("click",function(){
let _this = this;//把this保存下来
setTimeout(function(){
//修改背景色 使用this
_this.style.background = "pink";
},2000);
});
let ad = document.getElementById("ad");
ad.addEventListener("click",function(){
// let _this = this;
setTimeout(()=>{
//修改背景色 使用this
// _this.style.background = "pink";
this.style.background = "pink";
},2000);
});
- 使用箭头函数后,就不需要保存
this
了,因为箭头函数的this
指向箭头函数声明时所在的作用域的this
(第2行),而声明时所在的作用域的this
指向事件源ad
。因此,此时箭头函数中的this
指向ad
.
- 注意: 如果第二行的监听器中的回调函数写成箭头函数,则
this
不再指向事件源ad
,而是指向window
- 箭头函数的使用场景
{
name:"尚硅谷",
getName = () =>{
this.name; //报错,this指向的不是当前对象,而是window
}
}