You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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. Writing test() tells the browser: "Hey, run the code inside the test function 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 onclick attribute. You'd write something like this:
    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);
    
    Here, addEventListener needs to know which function to run when the click happens. If you wrote test() 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 is undefined in this case) to addEventListener — that's definitely not what we want!

Quick recap with your code

  • In your original code, onclick="test()" works because the browser executes the string test() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:23:42