user701254
user701254

Reputation: 3953

Why is this function being invoked?

I just want to assign a variable to a function so it can be invoked later but in this fiddel the function is invoked every time I press button 'invoke'

Should it not just assign the function to the varialbe 'fun' and not call the alert ?

fiddle : http://jsfiddle.net/vkvUR/

code :

$("#button").click(myFun);

    <input name="Button3" type="button" value="Invoke" id="button">

    function myFun(myarg){   
        var fun = alert(myarg); 

    }  

    function myFunParam(myFun){    
        if (typeof myFun === "function")       
            myFun('foo'); // alerts "foo" 
    } 

Upvotes: -1

Views: 71

Answers (3)

AlexMA
AlexMA

Reputation: 10214

alert(myFun) invokes the alert method which then causes a popup. Perhaps you meant something like this. When you pass parameters to a function within parens after the function name, it will be invoked. To reference a function without invoking it, leave out the parameters.

​var foo = alert;
foo("bar")​​​​​​​​​​​; //alerts "bar"

Upvotes: 0

Ahamed Mustafa M
Ahamed Mustafa M

Reputation: 3139

Change var fun = alert(myarg); to var fun = function(){alert(myarg)}; if you want to use variable fun later

Upvotes: 0

Curtis
Curtis

Reputation: 103378

You need to assign an anonymous function to fun containing your alert call.


Change:

var fun = alert(myarg); 

To:

var fun = function(){
   alert(myarg); 
}

http://jsfiddle.net/Curt/vkvUR/1/

And heres a version calling fun():

http://jsfiddle.net/Curt/vkvUR/2/

Upvotes: 2

Related Questions