JavaScript函数调用加()和不加()

注意
!!!加()表示立即执行
!!!不加()一般用在触发某个事件后才执行

下面代码调用不加()
(发生点击事件后才执行)

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        #box {
       
            width: 100px;
            height: 100px;
            background: red;
        }
    style>
head>

<body>
    <button id="btn1">按钮1button>
    <button id="btn2">按钮2button>
    <div id="box">div>
    <script>
        var btn1 = document.getElementById('btn1');
        var btn2 = document.getElementById('btn2');
        var box = document.getElementById('box');

         btn1.onclick = fn;
         btn2.onclick = fn;
         function fn() {
       
             box.style.width = '200px';
             box.style.height = '200px';
         }
        
    script>
body>

html>

下面代码调用加()
(直接执行函数)

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    <script>
        function fn() {
       
            alert(1);
        }
        fn();
    script>
body>

html>


要传递参数时一般放到行间且加()
与前面的规则有点不同

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        #box {
       
            width: 100px;
            height: 100px;
            background: red;
        }
    style>
head>

<body>
    <button id="btn1" onclick="fn('200px','200px')">按钮1button>
    <button id="btn2" onclick="fn('50px','50px')">按钮2button>
    <div id="box">div>
    <script>
        var btn1 = document.getElementById('btn1');
        var btn2 = document.getElementById('btn2');
        var box = document.getElementById('box');
        function fn(a, b) {
       
            box.style.width = a;
            box.style.height = b;
        }
    script>
body>

html>

你可能感兴趣的:(javascript)