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

相信前端開發(fā)者對 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 對象上, 并且還可以傳進(jìn)去額外的參數(shù), 當(dāng)返回的綁定函數(shù)被調(diào)用時, 這些額外的參數(shù)會自動傳入綁定函數(shù)。

現(xiàn)在我們對 bind() 有了初步的認(rèn)識, 我們先來看看 bind() 的基本用法:

const person = {
  sayHello() {
    console.log("Hello")
  }
}

const dog = {
  species: "single dog" 
}

現(xiàn)在我們有了兩個對象, 一個人, 一個狗(兩個對象聽起來怪怪的????), 我們怎樣才能讓狗利用人上的方法, 向你問好呢?

const dogSayHello = person.sayHello.bind(dog)
dogSayHello()

好了, 現(xiàn)在這條狗出色的完成了我們的任務(wù)。

了解 bind() 的基本用法之后, 我們來看看 bind() 的一些實用技巧:

一:創(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(), 這時會出現(xiàn)

A undefined is running!

這個是很多人都踩過的坑,因為這時 this 指向的并不是 dog 了, 而是全局對象(window/global)。那么怎么解決呢?我們可以把 run 方法綁定到特定的對象上, 就不會出現(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)建了一個綁定函數(shù),成功解決了我們經(jīng)常遇到的一個坑, 現(xiàn)在輪到人來解決另一個坑了!

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() 方法中傳入了一個匿名函數(shù)(anynomous function), 在匿名函數(shù)中, this 指向的是全局對象(window/global),而全局對象上并沒有我們調(diào)用的 eat() 方法。那我們現(xiàn)在該怎么辦?

方法一:既然使用 this 容易出問題, 那我們就不使用 this ,這是啥意思? 我們看代碼:

daily() {
    const self = this
    this.enjoy(function() {
      self.eat()
      self.drink()
      self.sleep()
    })
  }

我們把 this 保存在 self 中, 這時 self 指向的就是 person, 解決了我們的問題。 但是這種寫法JS新手看起來會有點奇怪,有沒有優(yōu)雅一點的解決辦法?

方法二:使用 ES6 中箭頭函數(shù)(aorrow function),箭頭函數(shù)沒有自己的 this 綁定,不會產(chǎn)生自己作用域下的 this 。

daily() {
    this.enjoy(() => {
      this.eat()
      this.drink()
      this.sleep()
    })
  }  

箭頭函數(shù)中的 this 是通過作用域鏈向上查詢得到的,在這里 this 指向的就是 person。這個方法看起來很不錯, 但是得用 ES6 啊, 有沒有既優(yōu)雅又不用 ES6 的解決方法呢?(這么多要求你咋不上天呢?。┯?! 我們可以利用 bind() 。

方法三:優(yōu)雅的 bind()。我們可以通過 bind() 把傳入 enjoy() 方法中的匿名函數(shù)綁定到了 person 上。

daily() {
    this.enjoy(function() {
      this.eat()
      this.drink()
      this.sleep()
    }.bind(this))
  }  

完美!但是現(xiàn)在還有一個問題:你知道一個人一生中最大的享受是什么嗎?

三:Event Listener

這里和上邊所說的回調(diào)函數(shù)沒太大區(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 元素, 我們怎么解決呢?通常我們是這樣做的:

 document.querySelector("button").addEventListener("click",  function() {
   dog.bark()
 })

這里我們寫了一個匿名函數(shù),其實這個匿名函數(shù)很沒必要, 如果我們利用 bind() 的話, 代碼就會變得非常優(yōu)雅簡潔。

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")
)

四:分離函數(shù)(Partial Functions)

我們傳遞給 bind() 的第一個參數(shù)是用來綁定 this 的,我還可以傳遞給 bind() 其他的可選參數(shù), 這些參數(shù)會作為返回的綁定函數(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. 欲望太多有時候是真累啊????

"a beautiful girlfriend" 作為 bind() 的第二個參數(shù),這個參數(shù)變成了綁定函數(shù)(personWant)的默認(rèn)參數(shù)。

五:setTimeout

這篇博客寫著寫著就到傍晚了,現(xiàn)在我(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 啊真是, 連狗都不會同意的!

六:快捷調(diào)用

天黑了,人和狗玩了一天都玩累了,回家睡覺去了……

現(xiàn)在我們來看一個我們經(jīng)常會碰到的例子:我們知道 NodeList 無法使用數(shù)組上的遍歷遍歷方法(像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() 方法就行了!

總結(jié):

請大家善待身邊的每一個 single dog! ??????

有哪里寫的不對的地方, 歡迎大家指正!

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容