JS bind() 方法之人和狗的故事

相信前端開(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ò)作用域鏈向上查詢(xún)得到的,在這里 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à), 代碼就會(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à), 我們家的狗的名字就會(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ì)的地方, 歡迎大家指正!

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容