<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="btn1">11111</button>
<button id="btn2">2222222222222</button>
<script>
let num=100;
//ES5 之前
var test1=function(n) {
return n*3;
};
console.log(test1(num));
//使用箭頭函數
let test2=(n) =>{
return n*3;
};
console.log(test2(num));
//如果參數只有一個, 連括號都可以省略了, 當然,兩個以上的就不能省略了,
// 基於上面的例子,因爲只有一條語句,一個參數,可以簡寫爲:
let test3=n => n*3;
console.log(test3(num));
//立即執行:
let test4=(()=> console.log(num*3))()
</script>
</body>
</html>
執行結果:
let test5 = {
content:"I'M test5",
init:function(){
// btn1.onclick = function () {
// console.log(this); //this指向的是 btn1 , 誰調用就指誰
// }
btn1.onclick = ()=> {
console.log(this); //箭頭函數完全修復了this的指向,this總是指向詞法作用域,也就是外層調用者 test5
}
}
};
test5.init();
let test56 = {
content:"I'M test6",
init:()=>{
btn2.onclick = ()=>{
console.log(this);// 因爲init用了箭頭函數,這裏的this 指的是 init的this: 就是window,
}
}
}
test56.init();
//另外, 箭頭函數不能當成構造函數來使用,並且其沒有prototype 屬性 和 arguments 對象
//還有一些需要注意的是,箭頭函數返回對象時,要加一個小括號
var func = () => ({ foo: 1 }); //正確
var func = () => { foo: 1 }; //錯誤