003-箭头函数

1. 箭头函数

let fn = function(){

}
//改写成箭头函数
let fn = ()=>{}
//调用
fn();//调用方法一样
  1. 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); //输出"尚硅谷"
  1. 不能作为构造函数实例化对象
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};
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);
});
{
name:"尚硅谷",
getName = () =>{
	this.name; //报错,this指向的不是当前对象,而是window
}
}