Reputation: 3877
i am trying to call self invoking function but it doesn't seem to work, as you can see code below i am able to alert (test) but not when it is called upon another function. Please advise - Thank you
var test = (function(a,b){
return a*b;
})(4,5);
function myFunc() {};
alert(test); // working
alert(test.call(myFunc, 10,5)); // not working
Upvotes: -1
Views: 186
Reputation: 536
An immediately invoking function is one that executes right when the script is loaded. In your example, the function next to test is executed right away, and it returns a value of 20.
I have a feeling what you really want is something like this:
var test = (function()
{
var a = 4,
b = 5;
return function()
{
return a*b;
}
}());
So in what I wrote above, test will NOT be set to 20. Instead, it'll be set to a function that multiplies a
against b
and returns 20. Why? Cause when I immediately invoke the function, it's not returning the actual value; it's returning yet another function, and that function then returns the actual value that I'm trying to calculate.
Upvotes: 0
Reputation: 652
You are evaluating the function at line 0, and assigning the return value "20" to test
. Since 20 is a number, not a function, you can't call it. Try instead:
var test = function(a,b){
return a*b;
};
alert(test(4,5));
alert(test(10,5));
Upvotes: 2