If i need to write a java script function that takes an argument and returns a function that returns that argument, i can think of following two implementations. Are both of these same ? or there is anything different technically ? Both works and returns the same result.
/*Implemenation 1*/
function myWieredFunc(arg){
var retf=function inner(){
return arg;
};
return retf;
}
/* Implemenation 2 */
function myWieredFunc(arg){
return function(){
return arg;
};
}
To use these:
var f = myWieredFunc(84);
alert(f());
-
2It does the same thing. You don't need the variable.elclanrs– elclanrs2014年02月08日 23:38:15 +00:00Commented Feb 8, 2014 at 23:38
-
And even in the first example, you don't need to name the inner function ("inner") at allIan– Ian2014年02月08日 23:48:35 +00:00Commented Feb 8, 2014 at 23:48
3 Answers 3
This would be the way to write it
function wrap(arg) {
return function() {
return arg;
};
};
If you wanted to make it more flexible you could allow multiple arguments:
function wrap() {
var args = arguments;
return function() {
return args;
};
};
var later = wrap('hello', 'world');
var result = later();
console.log(result); // ["hello", "world"]
Comments
There is no reason for the variable in the code shown - functions are objects are values. As you've shown this means that function-objects can be assigned to a variable which is later evaluated and returned, or returned directly from the Function Expression.
As such, both forms are generally held equivalent and the closure over arg is unaffected.
However, in the first form..
Function.toStringand stack-traces will normally include the function name, this makes "named functions", as in the first example sometimes more useful in debugging. Additionally, Firefox will expose function names - e.g. "inner" - through the non-standardFunction.nameproperty. (The function name can be specified without the use of theretfvariable.)Two additional bindings are introduced -
retfin the outer function andinnerin the inner function. These variables could be observed in the the applicable scope when stopping via a break-point - but are not otherwise accessible in the code shown.
Comments
They are the same thing, the second is using an "Anonymous" function which just means its a function that is not given a name or assigned to a variable.