相信前端開(kāi)發(fā)者對(duì) JavaScript 中的 bind() 方法都不會(huì)陌生面徽,這個(gè)方法很強(qiáng)大酝枢, 可以幫助解決很多令人頭疼的問(wèn)題府阀。
我們先來(lái)看看 MDN 對(duì) 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.
語(yǔ)法:fun.bind(thisArg[, arg1[, arg2[, ...]]])
簡(jiǎn)單來(lái)說(shuō)渡冻, 我們可以利用 bind() 把 fun() 方法中的 this 綁定到 thisArg 對(duì)象上砾赔, 并且還可以傳進(jìn)去額外的參數(shù)蔫骂, 當(dāng)返回的綁定函數(shù)被調(diào)用時(shí)么翰, 這些額外的參數(shù)會(huì)自動(dòng)傳入綁定函數(shù)。
現(xiàn)在我們對(duì) bind() 有了初步的認(rèn)識(shí)辽旋, 我們先來(lái)看看 bind() 的基本用法:
const person = {
sayHello() {
console.log("Hello")
}
}
const dog = {
species: "single dog"
}
現(xiàn)在我們有了兩個(gè)對(duì)象浩嫌, 一個(gè)人檐迟, 一個(gè)狗(兩個(gè)對(duì)象聽(tīng)起來(lái)怪怪的????), 我們?cè)鯓硬拍茏尮防萌松系姆椒ǎ?向你問(wèn)好呢码耐?
const dogSayHello = person.sayHello.bind(dog)
dogSayHello()
好了追迟, 現(xiàn)在這條狗出色的完成了我們的任務(wù)。
了解 bind() 的基本用法之后骚腥, 我們來(lái)看看 bind() 的一些實(shí)用技巧:
一:創(chuàng)建綁定函數(shù)
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, 然后在全局環(huán)境中調(diào)用 dogRun(), 這時(shí)會(huì)出現(xiàn)
A undefined is running!
這個(gè)是很多人都踩過(guò)的坑敦间,因?yàn)檫@時(shí) this 指向的并不是 dog 了, 而是全局對(duì)象(window/global)束铭。那么怎么解決呢廓块?我們可以把 run 方法綁定到特定的對(duì)象上, 就不會(huì)出現(xiàn) this 指向變化的情況了契沫。
const dogRun = dog.run.bind(this)
dogRun() // A single dog is running!
現(xiàn)在屏幕上出現(xiàn)了一條正在奔跑的狗带猴!
二:回調(diào)函數(shù)(callback)
在上面例子中,單身狗創(chuàng)建了一個(gè)綁定函數(shù)懈万,成功解決了我們經(jīng)常遇到的一個(gè)坑拴清, 現(xiàn)在輪到人來(lái)解決另一個(gè)坑了!
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() // 這里會(huì)報(bào)錯(cuò)会通。 TypeError: this.eat is not a function
我們?cè)?enjoy() 方法中傳入了一個(gè)匿名函數(shù)(anynomous function), 在匿名函數(shù)中口予, this 指向的是全局對(duì)象(window/global),而全局對(duì)象上并沒(méi)有我們調(diào)用的 eat() 方法渴语。那我們現(xiàn)在該怎么辦?
方法一:既然使用 this 容易出問(wèn)題昆咽, 那我們就不使用 this 驾凶,這是啥意思? 我們看代碼:
daily() {
const self = this
this.enjoy(function() {
self.eat()
self.drink()
self.sleep()
})
}
我們把 this 保存在 self 中掷酗, 這時(shí) self 指向的就是 person调违, 解決了我們的問(wèn)題。 但是這種寫(xiě)法JS新手看起來(lái)會(huì)有點(diǎn)奇怪泻轰,有沒(méi)有優(yōu)雅一點(diǎn)的解決辦法技肩?
方法二:使用 ES6 中箭頭函數(shù)(aorrow function),箭頭函數(shù)沒(méi)有自己的 this 綁定浮声,不會(huì)產(chǎn)生自己作用域下的 this 虚婿。
daily() {
this.enjoy(() => {
this.eat()
this.drink()
this.sleep()
})
}
箭頭函數(shù)中的 this 是通過(guò)作用域鏈向上查詢得到的,在這里 this 指向的就是 person泳挥。這個(gè)方法看起來(lái)很不錯(cuò)然痊, 但是得用 ES6 啊, 有沒(méi)有既優(yōu)雅又不用 ES6 的解決方法呢屉符?(這么多要求你咋不上天呢>缃)有锹引! 我們可以利用 bind() 。
方法三:優(yōu)雅的 bind()唆香。我們可以通過(guò) bind() 把傳入 enjoy() 方法中的匿名函數(shù)綁定到了 person 上嫌变。
daily() {
this.enjoy(function() {
this.eat()
this.drink()
this.sleep()
}.bind(this))
}
完美!但是現(xiàn)在還有一個(gè)問(wèn)題:你知道一個(gè)人一生中最大的享受是什么嗎躬它?
三:Event Listener
這里和上邊所說(shuō)的回調(diào)函數(shù)沒(méi)太大區(qū)別腾啥, 我們先看代碼:
<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 元素, 我們?cè)趺唇鉀Q呢虑凛?通常我們是這樣做的:
document.querySelector("button").addEventListener("click", function() {
dog.bark()
})
這里我們寫(xiě)了一個(gè)匿名函數(shù)碑宴,其實(shí)這個(gè)匿名函數(shù)很沒(méi)必要, 如果我們利用 bind() 的話桑谍, 代碼就會(huì)變得非常優(yōu)雅簡(jiǎn)潔延柠。
document.querySelector("button").addEventListener("click", dog.bark.bind(this))
一行搞定!
在 ES6 class
中 this 也是沒(méi)有綁定的锣披, 如果我們 ES6 的語(yǔ)法來(lái)寫(xiě) 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")
)
四:分離函數(shù)(Partial Functions)
我們傳遞給 bind() 的第一個(gè)參數(shù)是用來(lái)綁定 this 的雹仿,我還可以傳遞給 bind() 其他的可選參數(shù)增热, 這些參數(shù)會(huì)作為返回的綁定函數(shù)的默認(rèn)參數(shù)。
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. 欲望太多有時(shí)候是真累啊????
"a beautiful girlfriend" 作為 bind() 的第二個(gè)參數(shù)胧辽,這個(gè)參數(shù)變成了綁定函數(shù)(personWant)的默認(rèn)參數(shù)峻仇。
五:setTimeout
這篇博客寫(xiě)著寫(xiě)著就到傍晚了,現(xiàn)在我(Victor)和我家的狗(Finn)要出去玩耍了邑商, 我家的狗最喜歡的一個(gè)游戲之一就是追飛盤(pán)……
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) 去掉的話摄咆, 我們家的狗的名字就會(huì)變成undefined, 誰(shuí)家的狗會(huì)叫 undefied 啊真是人断, 連狗都不會(huì)同意的吭从!
六:快捷調(diào)用
天黑了,人和狗玩了一天都玩累了恶迈,回家睡覺(jué)去了……
現(xiàn)在我們來(lái)看一個(gè)我們經(jīng)常會(huì)碰到的例子:我們知道 NodeList 無(wú)法使用數(shù)組上的遍歷遍歷方法(像forEach, map)涩金,遍歷 NodeList 會(huì)顯得很麻煩。我們通常會(huì)怎么做呢暇仲?
<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() 方法就行了!
總結(jié):
請(qǐng)大家善待身邊的每一個(gè) single dog! ??????
有哪里寫(xiě)的不對(duì)的地方奈附, 歡迎大家指正辆床!
參考:
- 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