Js code understanding

problem description

A simple click of a button triggers the pop-up window function, and the conceptual details of the code are a little confusing

related codes

/ / method 1:

<script>
  function f1() {
    alert("");
  }
</script>
<input type="button" value="" onclick="f1()"/>  <!--f1()-->

method 2:

<input type="button" value="" id="btn" />

<script>
  function f2() {
    alert("htmljs");
  }
  function f2() {
    alert("");
  }
  var btnObj=document.getElementById("btn");
  //
  btnObj.onclick=f2;//
</script>

Why should I add parentheses to the f1 after the onclick attribute in mode 1 and not to f2 in mode 2?

Apr.09,2021

onclick= "F1 ()" is equivalent to the following code:


onclick <br>Function ()

<br>`<br>onclick = function (){

f1; 

}
`
because F1 is not executed immediately, executing anonymous functions has no effect

for mode 2, adding double parentheses indicates that the result of f2 execution is assigned to the onclick attribute, and f2 returns undefined, after execution, so there is no effect

Menu