manraj82
manraj82

Reputation: 6305

Function expression with Arguments

I was playing around with function expressions and trying to get my head round some stuff.This is the code I wrote.

This works

var sum=function(arg1,arg2){
    return(function(){alert(arg1*arg2)})
}

document.getElementById('button_1').onclick=sum(3,2);

This doesnt,I know it doesnt even look right.But Im just trying to understand the reason behind the error that was being displayed here.It first displayed the alert box with 6 then an error message "Not Implemented",this is in IE6.

var sum=function(arg1,arg2){
    alert(arg1*arg2);
}

document.getElementById('button_1').onclick=sum(3,2);

If you guys think this question doesn't require an answer please let me know,I will delete it.

Thanks

Upvotes: 3

Views: 5471

Answers (2)

domih
domih

Reputation: 1578

Using local variables is a preferred way as I have more control about when a function is called. Passing arguments to function expressions does not feel natural as it needs some strange syntax. Here is how I'm generally using functions in Javascript.

Declare a locally scoped function:
var enableStopBtn = function('videoBtnId') { // do something }

Call the variable: enableStopBtn('myVideob');

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

In the second example your sum variable doesn't return a function pointer. The onclick event must be assigned to a function pointer. So in this second example you are directly invoking the sum function by passing it two arguments and because this function doesn't return anything (it simply alerts) it doesn't work. To make it work with the second example you need:

document.getElementById('button_1').onclick = sum;

But once the button is clicked it will pass a single argument to this sum function which represents the event.

In the first example you invoke the sum function by passing it two arguments but this invocation simply returns another function which is then assigned to the onclick event.

I guess you want this though:

document.getElementById('button_1').onclick = function() { sum(3,2); };

Upvotes: 2

Related Questions