1.箭头函数的使用
<script>
let name=["小明","小绿","小白"];
let name_normal=name.map(function(item){
return item+="同学";
});
let name_arrow=name.map((item)=>{return item+="同学"});
// 最简单写法
// let name_arrow=name.map(item=> item+="同学");
// 最简单写法
console.log(name_normal);
console.log('\n');
console.log(name_arrow);
</script>
2.箭头函数不能用new创建(无构造能力,用完即弃)
Normal.prototype.name="哈哈哈";
function Normal(){}
const normal=new Normal();
console.log(normal.name); //输出结构内属性
// const Arrow=()=>{},
// const arrow=new Arrow();//无法正确创建结构
3.this的指向
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>箭头函数</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
*{
margin:0;
padding: 0;
}
body{
position: relative;
background: rgb(255,242,231);
}
.div2{
width: 500px;
height: 500px;
background: rgb(116,73,212);
position: fixed;
text-align: center;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
border-radius: 15px;
}
button{
margin:50px;
}
p{
font-size: 20px;
width: 300px;
margin: 30px auto;
border-radius: 15px;
background: rgb(253,110,139);
}
</style>
</head>
<body>
<div class="div2">
<button class="normalButton btn btn-info btn-lg">普通函数</button>
<p class="normalP"></p>
<button class="arrowButton btn btn-danger btn-lg">箭头函数</button>
<p class="arrowP"></p>
</div>
</body>
<script>
const normalButton=document.querySelector(".normalButton");
const arrowButton=document.querySelector(".arrowButton");
const normalP=document.querySelector(".normalP");
const arrowP=document.querySelector(".arrowP");
let normalFunction=function(){
normalP.innerHTML="普通函数"+this;
};
let arrowFunction=()=>{
arrowP.innerHTML="箭头函数"+this;
};
normalButton.addEventListener("click",normalFunction,false);
arrowButton.addEventListener("click",arrowFunction,false);
</script>
</html>
普通函数的this值是动态的
箭头函数的值是指向全局或上一层普通函数的this