简体   繁体   中英

Why is function() needed sometimes in JavaScript?

HTML

<button id='hello'>Click Me!</button>

JavaScript (wrong)

$('#hello').click(alert('Hello, World!'));

JavaScript (correct)

$('#hello').click(function() {
    alert('Hello, World!');
}

I'm wondering why the first JS code triggers on the event load instead of click . Can anyone tell me why function() { [code] } is needed for the script to work properly?

In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout , too.

The click function expects another function as a parameter.

In the first case you would be passing the result of calling alert('hello world'); , which is null.

The second is just a shorthand for:

$('#hello').click(callback);

function callback(){
  alert('hello world');
}

Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert ) and then pass it's return value.

Writing $('#hello ).click( function() { } )` is basically a short hand for writing:

var myfunction = function() { 
  // code
};

$('#hello').click( myfunction );

As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.

Your first example says "evaluate

alert('Hello, World!')

right now, and pass the result as an argument to click. "

The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.

The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.

You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:

function returnCallback(linkId, data) {
    return function(e) {
        alert('Clicked on ' + linkId + '.  Here is some data: ' + data);
        // Maybe do some stuff with e, the event parameter
    }
}

$('#some-link').click(returnCallback('some-link', 'some-data'));

$('#other-link').click(returnCallback('other-link', 'different-data'));

This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.

In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.

$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.

This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:

<script language="javascript" type="text/javascript">

    $("#mybutton").click(clickFired);


    function clickFired() {

        alert('click fired');
    }

</script>

The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().

The click function here assigns a value to the event handler.

With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.

With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.

somefunction(alert('hello! world'));

this would mean you want to pass to somefunction the return value of alert("hello! world").

jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM