相信前端開發者對 JavaScript 中的 bind() 方法都不會陌生,這個方法很強大, 可以幫助解決很多令人頭疼的問題。
我們先來看看 MDN 對 bind() 下的定義:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
語法:fun.bind(thisArg[, arg1[, arg2[, ...]]])
簡單來說, 我們可以利用 bind() 把 fun() 方法中的 this 綁定到 thisArg 對象上, 并且還可以傳進去額外的參數, 當返回的綁定函數被調用時, 這些額外的參數會自動傳入綁定函數。
現在我們對 bind() 有了初步的認識, 我們先來看看 bind() 的基本用法:
const person = {
sayHello() {
console.log("Hello")
}
}
const dog = {
species: "single dog"
}
現在我們有了兩個對象, 一個人, 一個狗(兩個對象聽起來怪怪的????), 我們怎樣才能讓狗利用人上的方法, 向你問好呢?
const dogSayHello = person.sayHello.bind(dog)
dogSayHello()
好了, 現在這條狗出色的完成了我們的任務。
了解 bind() 的基本用法之后, 我們來看看 bind() 的一些實用技巧:
一:創建綁定函數
const dog = {
species: "single dog",
run() {
console.log("A " + this.species + " is running!")
}
}
const dogRun = dog.run
dogRun() // A undefined is running!
我們把 dog 的 run 方法賦給 dogRun, 然后在全局環境中調用 dogRun(), 這時會出現
A undefined is running!
這個是很多人都踩過的坑,因為這時 this 指向的并不是 dog 了, 而是全局對象(window/global)。那么怎么解決呢?我們可以把 run 方法綁定到特定的對象上, 就不會出現 this 指向變化的情況了。
const dogRun = dog.run.bind(this)
dogRun() // A single dog is running!
現在屏幕上出現了一條正在奔跑的狗!
二:回調函數(callback)
在上面例子中,單身狗創建了一個綁定函數,成功解決了我們經常遇到的一個坑, 現在輪到人來解決另一個坑了!
const person = {
name: "Victor",
eat() {
console.log("I'm eating!")
},
drink() {
console.log("I'm drinking!")
},
sleep() {
console.log("I'm sleeping!")
},
enjoy(cb) {
cb()
},
daily() {
this.enjoy(function() {
this.eat()
this.drink()
this.sleep()
})
}
}
person.daily() // 這里會報錯。 TypeError: this.eat is not a function
我們在 enjoy() 方法中傳入了一個匿名函數(anynomous function), 在匿名函數中, this 指向的是全局對象(window/global),而全局對象上并沒有我們調用的 eat() 方法。那我們現在該怎么辦?
方法一:既然使用 this 容易出問題, 那我們就不使用 this ,這是啥意思? 我們看代碼:
daily() {
const self = this
this.enjoy(function() {
self.eat()
self.drink()
self.sleep()
})
}
我們把 this 保存在 self 中, 這時 self 指向的就是 person, 解決了我們的問題。 但是這種寫法JS新手看起來會有點奇怪,有沒有優雅一點的解決辦法?
方法二:使用 ES6 中箭頭函數(aorrow function),箭頭函數沒有自己的 this 綁定,不會產生自己作用域下的 this 。
daily() {
this.enjoy(() => {
this.eat()
this.drink()
this.sleep()
})
}
箭頭函數中的 this 是通過作用域鏈向上查詢得到的,在這里 this 指向的就是 person。這個方法看起來很不錯, 但是得用 ES6 啊, 有沒有既優雅又不用 ES6 的解決方法呢?(這么多要求你咋不上天呢!)有! 我們可以利用 bind() 。
方法三:優雅的 bind()。我們可以通過 bind() 把傳入 enjoy() 方法中的匿名函數綁定到了 person 上。
daily() {
this.enjoy(function() {
this.eat()
this.drink()
this.sleep()
}.bind(this))
}
完美!但是現在還有一個問題:你知道一個人一生中最大的享受是什么嗎?
三:Event Listener
這里和上邊所說的回調函數沒太大區別, 我們先看代碼:
<button>bark</button>
<script>
const dog = {
species: "single dog",
bark() {
console.log("A " + this.species + " is barking")
}
}
document.querySelector("button").addEventListener("click", dog.bark) // undefined is barking
</script>
在這里 this 指向的是 button 所在的 DOM 元素, 我們怎么解決呢?通常我們是這樣做的:
document.querySelector("button").addEventListener("click", function() {
dog.bark()
})
這里我們寫了一個匿名函數,其實這個匿名函數很沒必要, 如果我們利用 bind() 的話, 代碼就會變得非常優雅簡潔。
document.querySelector("button").addEventListener("click", dog.bark.bind(this))
一行搞定!
在 ES6 class
中 this 也是沒有綁定的, 如果我們 ES6 的語法來寫 react 組件, 官方比較推薦的模式就是利用 bind() 綁定 this。
import React from "react"
import ReactDOM from "react-dom"
class Dog extends React.Component {
constructor(props) {
super(props)
this.state = { barkCount: 0 }
this.handleClick = this.handleClick.bind(this) // 在這里綁定this
}
handleClick() {
this.setState((prevState) => {
return { barkCount: prevState.barkCount + 1 }
})
}
render() {
return (
<div>
<button onClick={this.handleClick}>
bark
</button>
<p>
The {this.props.species} has barked: {this.state.barkCount} times
</p>
</div>
)
}
}
ReactDOM.render(
<Dog species="single dog" />,
document.querySelector("#app")
)
四:分離函數(Partial Functions)
我們傳遞給 bind() 的第一個參數是用來綁定 this 的,我還可以傳遞給 bind() 其他的可選參數, 這些參數會作為返回的綁定函數的默認參數。
const person = {
want() {
const sth = Array.prototype.slice.call(arguments)
console.log("I want " + sth.join(", ") + ".")
}
}
var personWant = person.want.bind(null, "a beautiful girlfriend")
personWant() // I want a beautiful girlfriend
personWant("a big house", "and a shining car") // I want a beautiful girlfriend, a big house, and a shining car. 欲望太多有時候是真累啊????
"a beautiful girlfriend" 作為 bind() 的第二個參數,這個參數變成了綁定函數(personWant)的默認參數。
五:setTimeout
這篇博客寫著寫著就到傍晚了,現在我(Victor)和我家的狗(Finn)要出去玩耍了, 我家的狗最喜歡的一個游戲之一就是追飛盤……
const person = {
name: "Victor",
throw() {
console.log("Throw a plate...")
console.log(this.name + ": Good dog, catch it!")
}
}
const dog = {
name: "Finn",
catch() {
console.log("The dog is running...")
setTimeout(function(){
console.log(this.name + ": Got it!")
}.bind(this), 30)
}
}
person.throw()
dog.catch()
如果這里把 bind(this) 去掉的話, 我們家的狗的名字就會變成undefined, 誰家的狗會叫 undefied 啊真是, 連狗都不會同意的!
六:快捷調用
天黑了,人和狗玩了一天都玩累了,回家睡覺去了……
現在我們來看一個我們經常會碰到的例子:我們知道 NodeList 無法使用數組上的遍歷遍歷方法(像forEach, map),遍歷 NodeList 會顯得很麻煩。我們通常會怎么做呢?
<div class="test">hello</div>
<div class="test">hello</div>
<div class="test">hello</div>
<div class="test">hello</div>
<script>
function log() {
console.log("hello")
}
const forEach = Array.prototype.forEach
forEach.call(document.querySelectorAll(".test"), (test) => test.addEventListener("click", log))
</script>
有了 bind() 我們可以做的更好:
const unbindForEach = Array.prototype.forEach,
forEach = Function.prototype.call.bind(unbindForEach)
forEach(document.querySelectorAll(".test"), (test) => test.addEventListener("click", log))
這樣我們以后再需要用到遍歷 NodeList 的地方, 直接用 forEach() 方法就行了!
總結:
請大家善待身邊的每一個 single dog! ??????
有哪里寫的不對的地方, 歡迎大家指正!
參考:
- JavaScript The Definitive Guide
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
- https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/#comments
- http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback