---
tags: JavaScript, hexo部落格
title: 箭頭函式與 this(下) - call、apply、bind
---
## 函式的內建方法與關鍵字
在箭頭函式與 this(上)中提到,箭頭函式沒有這些方式可以用 :
- `this`
- `arguments`
- `call()`
- `apply()`
- `bind()`
這篇我們要來看這些東西原本是怎麼運作的。
### 關鍵字 this
複習一下 `this` 的運作 :
```javascript
var person = {
name: 'Vic',
age: 18,
whoAmI: function(){
console.log(`我是${this.name},今年${this.age}歲`)
}
}
person.whoAmI()
// 由於是在物件呼叫此函式的,所以往上一層尋找時(非箭頭函式),會找到此物件的屬性值
```
### 關鍵字 arguments
- 一般函式內建的關鍵字之一
- 可以將傳入的參數值抓取出來形成一個類陣列**物件**
```javascript
function sum(a, b) {
console.log(arguments[0])
console.log(typeof(arguments))
}
sum(2, 4)
// 2
// "object"
```
### 內建函式 call、apply、bind的共通點
- JS的內建函式
- 它們都與 `this` 有所關聯
- 不需要在函式中自訂參數就能將變數塞進 `this`
- 若有多個值,函式的第一個參數位置為 `this`
- 也就是說`(this, 參數1, 參數2, 以此類推)`
接下來,我們來看,`call()`、`apply()`以及 `bind()` 如何與 `this` 運作。
### 內建函式 call
- 單純將參數值傳入
```javascript
function sum(a) {
console.log(`this為${this}`)
console.log(`第二個是${a}`)
console.log(this + a)
}
sum.call(2, 4)
// "this為2"
// "第二個是4"
// 6
```
### 內建函式 apply
- 傳入的型態必須是陣列
- 功能上與 `call` 無異
```javascript
function sum(a, b) {
console.log(`陣列中第一個是${a}`)
console.log(`this為${this}`)
console.log(`陣列中第二個是${b}`)
console.log(this + a + b)
}
let array = [2, 4]
sum.apply(1, array)
// "陣列中第一個是2"
// "this為1"
// "陣列中第二個是4"
// 7
```
### 內建函式 bind
- **`bind()`將建立一個新的函式**
```javascript
// 範例一
// bind會建立一個新的函式
// this會對應傳入的參數 newPerson
var name = 'Jay'
function display(){
console.log(this.name)
}
var newPerson = {
name: 'Vic'
}
var newDisplay = display.bind(newPerson)
display() // Jay
newDisplay() // Vic
// 新的函式會執行 console.log(newPerson.name)
```
```javascript
// 範例二
// 若有多個值,bind的參數第一順位為 'this'
function sum(a) {
console.log(`第一個是${this}`)
console.log(`第二個是${a}`)
console.log(this + a)
}
let plusTwo = sum.bind(2, 4)
plusTwo()
// "第一個是2"
// "第二個是4"
// 6
```
## 箭頭函式與 this
我們了解到箭頭函式沒有自己的 `this`,相對的也就沒有上述的那三種內建函式可供使用,也無法使用 `arguments`,但可以改用其餘參數來達成目的。箭頭函式與一般函式的運用,還是得看實際情況來做使用。
## 參考來源
> 1. [realdennis - [JavaScript] 函數原型最實用的 3 個方法 — call、apply、bind](https://medium.com/@realdennis/javascript-%E8%81%8A%E8%81%8Acall-apply-bind%E7%9A%84%E5%B7%AE%E7%95%B0%E8%88%87%E7%9B%B8%E4%BC%BC%E4%B9%8B%E8%99%95-2f82a4b4dd66)
> 2. [Schaos - 一次搞懂前端面試最愛問的 apply、bind、call](https://medium.com/schaoss-blog/%E4%B8%80%E6%AC%A1%E6%90%9E%E6%87%82%E5%89%8D%E7%AB%AF%E9%9D%A2%E8%A9%A6%E6%9C%80%E6%84%9B%E5%95%8F%E7%9A%84-apply-bind-call-708f57518776)
> 3. [Henry Chang - JavaScript - call,apply,bind](https://ithelp.ithome.com.tw/articles/10195896)