user2703642
user2703642

Reputation: 193

Why shouldn't the function within a function of an onclick-event have parentheses?

I was battling with this problem for a while:

<input type="submit" onclick="barPlot(function1())">
<input type="submit" onclick="barPlot(function2())">

Where I tried to, via an onclick event, allow my "barPlot()" function to pick data from various functions.

The result of this in my barPlot function which looked like this...:

function barPlot(callback) {

    var myData = callback();

    }

...was "callback is not a function".

When I finally tried this (removing the end-parentheses in the call) it worked:

<input type="submit" onclick="barPlot(function1)">
<input type="submit" onclick="barPlot(function2)">

Why is that?

(If someone has some additional critique of my way of doing this, then you are allowed to freely mention it. This is practice for me).

Upvotes: 1

Views: 47

Answers (2)

moronator
moronator

Reputation: 303

It happens because you have to provide a function as a callback, but if you write parentheses, you don't provide a function. Instead your execute the written function (due to the parentheses) and provide the value returned by it.

Upvotes: 1

VictorArcas
VictorArcas

Reputation: 630

Because if you add the parenteshes you are making a call to that function and giving the outer function the value returned by the execution of the inner one.

Upvotes: 2

Related Questions