Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - How could it be possible to pass arguments to inner function inside another one with same name?

I'm new to JavaScript and learning it from Freecodecamp. here is one of script while learning higher order arrow function. I can't understand it completely, is there two function with same name in the example below? where do the arguments passed in? inside inner function or outer one? if the answer is outer function, how could it be possible as the outer function seems like doesn't take any argument.

const increment = (function(){
    return function increment(number, value){
        return number + value;
    };
})();
console.log(increment(5,2));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The function assigned to the increment constant is wrapped an IIFE (Immediately Invoked Function Expression). This means that this function is, like the name suggests, immediately called and executed. It then returns a reference to the function declared inside the IIFE.

const increment = (function(){
  return function increment(number, value){
    return number + value;
  };
})();

This results is the same as this:

const increment = function increment(number, value){
  return number + value;
};

This is a named function expression. Both the variable and the function are allowed to have the same name if you follow this pattern. Try defining it in the console like how it is in the second code block.

The difference here is that the variable increment is simply a reference to the function increment.

But in your case the function increment was defined inside the anonymous function's scope. The increment function name is then only available in the scope of that anon function. The reference to the increment function is then returned.

Though the IIFE can be omitted as it doesn't do anything different. It could add some value if you want to incorporate a closure to hide some variables, for example:

const increment = (function(){
  const hiddenValue = 2;
  return function increment(number, value){
    return number + value + hiddenValue;
  };
})();

Now everytime you call increment the hiddenValue will be added to the formula. This way you can create a kind of global variable which lives in the scope of the IIFE and won't pollute your actual global scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...