Is there any difference betwwen these two approaches(bind a function to button with parameter) in JavaScript?
Solution 1:
It's vanishingly unlikely, but it's theoretically possible for there to be a difference in behavior.
In strict mode, this
doesn't have to be an object. If you do greet.bind(null
, the this
will be null
- and if you do greet()
, the this
will be undefined
.
'use strict';
const someButton = document.querySelector('.btn');
function greet() {
console.log(this);
}
someButton.addEventListener('click', function() {
greet('Max');
});
someButton.addEventListener('click', greet.bind(null, 'Max'));
<button class="btn">click</button>
But for any even halfway reasonable code, this difference would not be something anyone should be testing - in which case those two approaches are identical for all intents and purposes.
Though, since it looks like greet
isn't intending to use any this
, you could consider just not modifying it at all, and just pass it as the handler itself:
someButton.addEventListener('click', greet);
which I'd consider to be perfectly reasonable (and, importantly, a bit easier to make sense of at a glance).