问题
I am not able to understand how this addItem()
and removeItem()
is called without parenthesis in addEventListener('click', addItem)
.
var addButton = document.getElementById('add');
addButton.addEventListener('click', addItem);
var removeButton = document.getElementById('remove');
removeButton.addEventListener('click', removeItem);
function addItem(){
console.log('Add Button clicked');
}
function removeItem(){
console.log('Remove Button clicked');
}
回答1:
Because in this context, addItem
is used as a function reference rather than the return value of the function.
If you did this:
addButton.addEventListener('click', addItem());
Then addItem
would be executed straight away, and whenever addButton
was clicked, the return value of addItem
(which is undefined
) would be called. This would result in an error, because undefined
is not a function.
Here, you're saying when I click addButton
, lookup the function reference I passed, and execute it.
You can also write this two different ways:
addButton.addEventListener('click', "addItem()");
addButton.addEventListener('click', function() {
addItem();
});
Both of the above will still result in the same output as your original code.
回答2:
This is because you are passing the function as an argument/parameter to the addEventListener()
method. If you add the parathesis, the function would execute straight away and that is not what you want. You're telling the addEventListener()
which function to execute when the event is fired.
Hope this helps.
回答3:
This is core js functionality. You can read about this here.
Functions are function objects. In JavaScript, anything that is not a primitive type ( undefined , null , boolean , number , or string ) is an object. Objects in JavaScript are extremely versatile. Because of this, we can even pass a function as a parameter into another function
回答4:
You are attaching an event listener and it will call the function If you add the parentesis inside the callback you will recive error because you exec the call
回答5:
Without parentheses you're not actually calling the function. A function name without the parentheses is a reference to the function.
来源:https://stackoverflow.com/questions/56423797/how-the-function-is-used-without-parenthesis-in-addeventlistener