What is happening in this code the Event parameter would be a this?

Asked

Viewed 21 times

0

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Document</title>
</head>
<body>
    
<script>

window.addEventListener("contextmenu", function(event)
{
    event.preventDefault();
});
    
</script>

</body>
</html>

The code on top of 4 lines is very simple, but it generated a doubt about the Event parameter (could be any parameter). When you create a parameter but do not define its value it is underfine correct ? in this case when I added the event contextmenu in the window and when this event occurs he will call an anonymous function cancelling the event contextmenu. But in this case it wouldn’t be like undefined.preventDefault() this parameter event has what value? and is referring to what ? would be a this ?

1 answer

1


In that case event is an object of the type MouseEvent.

He is not undefined because you are not declaring it, you are receiving it. The value of event is defined by the code that will invoke its anonymous function.

Take for example:

function gerarEvento(callBack) {
    callBack({ tipo: 'click', momento: Date.now() })
}

gerarEvento(function(evento) {
    console.log(evento.tipo)
    console.log(evento.momento)
})

What is the value of evento here? It is an object with the properties tipo and momento, object defined by the code that received the anonymous function, and invoked it passing this value as parameter. This is what happens in the addEventListener, a code from behind receives its anonymous function, and invokes it by passing an object, in this case, a MouseEvent.

  • Then, in this case the Event parameter would be an object with various information contained in it ?

  • 1

    Yes, event is an object with several properties, including the method preventDefault that you invoke. You can check all the properties of it here (remembering that he also inherits the properties of Event), or just make a console.log in it.

  • So thank you very much @user140828 helped a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.