This confused me a lot
var show = function(){
console.log('wow');
};
var show2 = function(word){
console.log(word);
};
button_element.addEventListener('click', show2('wow'), false)
‘wow’ //it return the string immediately but hit the button, nothing output in the console,
but
button_element.addEventListener('click', show. false)
No string return as we expect and then hit the button wow shows in the console as intended
anybody explain why does it act this way?
addEventListenertakes a function as its second argument. Once you call a function, it means you’re passing the returned value of that function, not the function itself. If you want to use a function call inaddEventListenerlike you’re trying to do, you should add a nested function that gets returned when you call it.Try this:
In the example above, the call to
addEventListeneris sent the inner function, which will have the captured value of thewordvariable within it.