ES6_箭頭函式

簡化後的箭頭函式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//宣告函式
function double(n){
return n*2;
}

var double = function(n){
return n*2;
}

//箭頭函示
const double = (n)=>{
return n*2;
}

//簡化箭頭函示
//如果只有一個參數,可以省略括號
const double = n =>{
return n*2
}

//簡化箭頭函示
//如果函式本體只有一行,且return一個值,可以省略大括號、return
const double = n => n*2
})

箭頭裡的this

箭頭沒有自己的情境(context),它內部的context就等於它外面的context,函式在哪裡被宣告函式,它裡面的this就代表被宣告時的環境。

如果,把函式改成箭頭函式,因為宣告函式的環境是global,因此箭頭函式中的this就代表global環境的物件,也就是window,不論用哪種方式執行函式一樣

1
2
3
4
const jump =()=>{
console.log(this)//this是window
}
jump();
1
2
3
4
5
6
7
const jump =()=>{
console.log(this)//this是window
}

const a = {};
a.jump = jump;
a,jump();

函式裡的this

第一種:直接執行函式,this代表window

1
2
3
4
function jump(){
console.log(this);//this是window
}
jump();

第二種:函式作為物件的方法來執行,其中的this代表物件本身

1
2
3
4
5
6
7
function jump(){
console.log(this);//this是a
}

const a = {};
a.jump = jump;
a.jump();

第三種:函式作為DOM的偵聽函式,其中的this代表DOM元件

1
2
3
4
5
6
7
8

<button id="btn">btn</button>

function jump(){
console.log(this);//this是 <button id="btn">btn</button>
}

btn.addEventListener("click",jump);