Reputation: 599
Considering the following code snippet,
function outer(data1){
function inner(){
console.log(data1);
}
return inner;
}
in the following two function calls, first one works but not the second one.
var o = outer("sree");
o(); //works
outer("kumar"); //does not work
Please help me to understand better. Thanks.
Upvotes: 2
Views: 56
Reputation: 3721
function outer(data1){
return (function inner(){
return data1;
});
}
The function outer returns another function 'inner', this is kind of a reference and to execute a function we need to call just like we called outer.
var o = outer("sree");
console.log(o()); The variable o contains ref to the function inner. to execute it we need to call (o()). In your last action (console.log(outer("kumar"))), you have invoked first function and it resulted ref to 'inner' function, to get the output you have to invoke the second as well. The kumar will get printed as because the 'inner' method is with in the scope of the outer function.
Upvotes: 0
Reputation: 346
When you invoke the function outer("kumar")
the function return a function, but that function is not invoked, that's the reason why this call do not log in console.
In the other hand, if you create a new variable invoking the function var o = outer("sree");
, as I mentioned, the function outer return a function inner, then you invoke that function with the new variable created o();
.
Upvotes: 1
Reputation: 251
You're inner function has no parameters, you need to add one like this:
function outer(){
function inner(data1){
console.log(data1);
}
return inner;
}
You're code will always log in the console the parameter with which you created the object.
Upvotes: 1
Reputation: 2234
Call like this:
outer("kumar")();
outer("kumar");
calling this will only get the reference of the inner function. By placing braces again it will call the inner function as well.
Upvotes: 4