Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

javascript - How the function is used without parenthesis in addEventListener?

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');
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...