箭頭函數
箭頭函數的特點
- 能夠使函數的寫法更加簡潔(一行寫完一個函數)
- 函數返回值可以被隱式返回(不需要寫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);