Search code examples
javascriptbind

Javascript .bind() doesn't work in this example?


Here is the code:

var num = 0
window.onload = function() {
    var button = document.getElementById('button')
    button.onclick = function() {
        addNum.bind(this)
  }
}
function addNum() {
    num++
    this.textContent = `hit ${num} times`
}

addNum.apply(this) and addNum.call(this) both work. I am confused. Anyone can help? Thanks a lot!


Solution

  • bind creates a new function, with a bound this value (and possibly arguments). If you want to execute the function, call it with ():

    button.onclick = function() {
      addNum.bind(this)();
    }
    

    But that's pretty silly to do when .call accomplishes the same thing, without requiring an extra ():

    button.onclick = function() {
      addNum.call(this);
    }
    

    Calling .bind without executing the created function is similar to:

    button.onclick = function() {
      const someFn = () => console.log('foo');
    }
    

    Here, you created a function named someFn, but never called it. Unless you call the resulting function, it'll go unused.