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

作者: 背着灯笼 | 来源:发表于2016-11-02 16:16 被阅读311次

    相信前端开发者对 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! 😂😂😂

    有哪里写的不对的地方, 欢迎大家指正!

    参考

    相关文章

      网友评论

      本文标题:JS bind() 方法之人和狗的故事

      本文链接:https://www.haomeiwen.com/subject/hogvuttx.html