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
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); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With