JavaScript事件处理函数调用疑问:为何有时加()有时不加?
Why do we add
() when calling a JavaScript function sometimes, but not other times? Great question! This is a super common point of confusion when starting out with JavaScript, so let's break it down using your example to make it crystal clear.
When to use () (parentheses)
- You add parentheses when you want to immediately execute the function and run its code right away.
- In your HTML, the
onclick="test()"attribute holds a snippet of JavaScript that the browser runs when the button is clicked. Writingtest()tells the browser: "Hey, run the code inside thetestfunction now!" - For example, if you added
test()directly inside your<script>tag (outside the function), it would run as soon as the script loads, updating the<p>element immediately without waiting for a click:function test() { document.getElementById("p1").innerHTML = "Hello World"; } // Runs right away when the script loads test();
When NOT to use ()
- You omit parentheses when you want to pass the function itself as a reference (callback) to another piece of code, letting that code decide when to execute it.
- Let's say you used modern event binding instead of the HTML
onclickattribute. You'd write something like this:
Here,function test() { document.getElementById("p1").innerHTML = "Hello World"; } const button = document.querySelector('input[type="button"]'); // Pass the function reference — no parentheses! button.addEventListener('click', test);addEventListenerneeds to know which function to run when the click happens. If you wrotetest()instead, the function would run immediately when the script loads (not when the button is clicked), and you'd be passing its return value (which isundefinedin this case) toaddEventListener— that's definitely not what we want!
Quick recap with your code
- In your original code,
onclick="test()"works because the browser executes the stringtest()as JS code on click — the parentheses trigger the function to run. - If you changed it to
onclick="test", the browser would just reference the function but never execute it, so clicking the button would do nothing at all.
内容的提问来源于stack exchange,提问作者Help123
相关产品推荐
相关产品推荐

