bernie2436
bernie2436

Reputation: 23901

Why can I pass a statement but not a function to this JS?

I know that you can have functions as parameters in JS.

When I pass the statement alert("d") as a parameter -- everything fires.

 dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
    }, alert("d"));

But when I pass a full on function -- the statement just does not fire.

 dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
    }, function() {
    alert("d");
});

Why might alert fire -- but the anonymous function not fire?

Upvotes: 0

Views: 46

Answers (3)

Shomz
Shomz

Reputation: 37701

You're simply not calling the function in the second method. I think this, third variation might help you understand it better, along with Scott's answer:

dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
    }, function() {
        alert("d");
    }() // <- note the () here
);

Sending just a function would be similar to just doing:

dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
}, alert
);

So my first example here (sort of) matches your first example, as the functions as called, not just passed it. Also, my second example matches your second example, as we're just passing in the function body as a parameter.

To understand on the simplest example how it works, compare the values of the variables in these cases:

var a = alert;
var a = alert('hey');

And they try, for example:

a('hello there'); // for both cases

Upvotes: 0

unsafe_where_true
unsafe_where_true

Reputation: 6300

In the first case you are calling the function, in the second you are passing a function body but it's not being called.

Upvotes: 2

Scott Sauyet
Scott Sauyet

Reputation: 50787

In the first case, you are calling alert("d") and passing the result of that, undefined, as the third parameter to the function. So the alert runs before your load function is even called. In the second case, the third parameter is an actual function, which, if it is ever called will perform the alert. It looks as though it is never called. You need to investigate the behavior of the dc.embed.load function and see how and when it calls the function you pass as its third parameter.

Upvotes: 5

Related Questions