箭头函数是ES6中新增的使用胖箭头(=>)定义函数的方法
箭头函数省略了关键字function
箭头函数的声明和调用
<script type="text/javascript">
let fun1 = function(a,b){
return a + b
};
let fun2 = (a,b) => {
return a + b
};
let result = fun2(1,2)
</script>
箭头函数使用中的注意事项
window.name = "window"
let obj = {
name:"Penrose",
getName:() =>{
console.log(this.name);
}
};
obj.getName()
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.demo{
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="demo"></div>
<script type="text/javascript">
let div = document.querySelector(".demo");
div.addEventListener("click",function(){
setTimeout(()=>{
this.style.backgroundColor = "purple";
},2000)
})
</script>
</body>
</html>
<script type="text/javascript">
let Person = (name,age) =>{
this.name = name;
this.age = age;
};
let p = new Person("Penrose",22)
</script>
<script type="text/javascript">
let fn = () =>{
console.log(arguments)
}
fn(1,2,3)
</script>
- 箭头函数的缩写:
- 有且仅有一个形参时可以省略小括号
- 有且仅有一行代码时可以省略花括号,并且需要省略return
|