箭头函数
箭头函数的特点
- 能够使函数的写法更加简洁(一行写完一个函数)
- 函数返回值可以被隐式返回(不需要写return)
- 不重新绑定this的值
函数改写
三种传参写法小练习
//函数一开始不传值
const greeting = () => {
console.log("hello world");
};
greeting();
//传一个值
const printName = (name) => {
return "hello "+name
};
console.log(printName("Mike"));
//传2个值
const total = (a,b) => {
return a+b;
};
console.log(total(3,5))
输出结果
注意,这里只有传一个参数的情况下才可以将括号去除
甚至可以去除大括号和return ,【注意】这个是只针对函数内容只有一行的情况
//传一个值
const printName = name => "hello "+name;
console.log(printName("Mike"));
尝试写一个数组
//数组
const companies = ["google","huawei","samsung"];
const result =companies.map(function(company){
return company + "is a company";
})
console.log(result);
//输出结果
(3) ["googleis a company", "huaweiis a company", "samsungis a company"]
//改进后
//数组
const companies = ["google","huawei","samsung"];
const result =companies.map(company=> company + "is a company");
console.log(result);
//筛选年龄大于20的数
const ages = [15,38,11];
const result2 = ages.filter(age => age>20)
console.log(result2);
//再加一行函数的情况下,return 不可省略
const ages = [15,38,11];
const result2 = ages.filter(age => {
const NextYearAge = age + 1;
return NextYearAge>20;
})
console.log(result2);
箭头函数与this
这里查看原始函数中this的指向
<!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>
#wrap {
width:100%;
}
#the-button {
display:block;
margin:50% auto;
}
.bigger {
padding:20px;
transition:padding 1s;
}
</style>
</head>
<body>
<div id="wrap">
<button id="the-button">click me</button>
</div>
<script>
document.getElementById("the-button").addEventListener("click",function(){
console.log(this)
this.classList.add("bigger")
});
</script>
</body>
</html>
输出结果是
换成箭头函数后的指向
document.getElementById("the-button").addEventListener("click",() => {
console.log(this)
this.classList.add("bigger")
});
再在函数体外加一层打印
console.log(this)
document.getElementById("the-button").addEventListener("click",() => {
console.log(this)
this.classList.add("bigger")
});
可以发现函数体内的this和函数外的this是指向的同一个内容
可以理解为箭头函数在调用的函数中,增加绑定是绑定不上去的。
函数体内的this在函数嵌套时需注意,无调用该函数的函数的情况下,this会自动归还给window
这里可考虑修改一下,借用箭头函数,因为箭头函数不会让this重新绑定
document.getElementById("the-button").addEventListener("click",function() {
this.classList.add("bigger");
setTimeout(()=>{
console.log(this);
this.innerHTML="clicked"
},1000)
});
随堂练习
我的答案
const pass = points => points >=60;
console.log(pass(81));
const sayYes = ()=> "yes";
console.log(sayYes());
const words=["moooo","da","yy"];
const ding=words.filter(word => word.length>3)
console.log(ding);