Reputation: 61
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!
Upvotes: 2
Views: 984
Reputation: 7
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';
}
});
Upvotes: 0
Reputation: 72177
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();
}
}
Upvotes: 0
Reputation: 4097
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.
Upvotes: 4