简体   繁体   中英

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!

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.

While you can see the effects of addNum.call() and addNum.apply() (the addNum() function is executed and it changes something on the page), addNum.bind(this) does not have any side effect.

Function.bind() does not call the functions used to invoke it, it creates and returns another function. But your code simply ignores the returned value.

Your code should be along this lines:

window.onload = function() {
    var button = document.getElementById('button')
    var boundAddNum = addNum.bind(this);
    button.onclick = function() {
        boundAddNum();
  }
}
var num = 0;
$(function() {
var button = document.getElementById('button');
button.onclick = function() {
var addNumX  = addNum.bind(this);
addNumX();
}
var addNum = function() {
num++;
alert("OK");
this.textContent = 'hit ${num} times';
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM