[英]Self-Executing Anonymous Functions Parameter From Outside Scope
I came across below code by following a tutorial.我按照教程遇到了下面的代码。
const increment = (function(){
return function incrementbytwo (number){
return number+2;
}
})();
console.log(increment(1));
The above outputs 3.以上输出3。
My problems are我的问题是
incrementbytwo
receive a parameter from outside since it's a Self-Executing Anonymous Functions
?incrementbytwo
如何从外部接收参数,因为它是一个Self-Executing Anonymous Functions
?Here is my understanding of this:以下是我对此的理解:
I will start with #2 on your list, as it will make this easier.我将从您列表中的 #2 开始,因为它会使这更容易。 What you have, is a self-executing anonymous function that RETURNS a stored function.
你所拥有的是一个自动执行的匿名函数,它返回一个存储的函数。
increment
constant to the returned result of the anonymous function's execution.increment
常量分配给匿名函数执行的返回结果。incrementbytwo
and THIS is assigned to your increment
constantincrementbytwo
并且 THIS 被分配给你的increment
常量increment
constant, which is now incrementbytwo(number)increment
常量中执行存储的函数,它现在是 incrementbytwo(number) Your code above is just a standard function declaration with extra steps at declaration.你上面的代码只是一个标准的函数声明,在声明时有额外的步骤。
const increment = function increment(number){
return number+2;
}
console.log(increment(1));
There is no production use for this exact code scenario as far as I know (Roast me in the comments if I am wrong)据我所知,这个确切的代码场景没有生产用途(如果我错了,请在评论中告诉我)
1) The self executing IFFE results in the creating of a function statement being assigned to the increment
identifier. 1) 自执行 IFFE 导致创建一个分配给
increment
标识符的函数语句。 It is exactly the same as:它与以下内容完全相同:
const increment = function incrementbytwo (number){
return number+2;
}
I should add, in case you don't know, that increment
is block scoped to the enclosing code block (const), while incrementbytwo
is function scoped to the function and is not accessible outside the function itself (due to the nature of the function expression).我应该补充一点,如果您不知道,该
increment
的块范围是封闭的代码块 (const),而incrementbytwo
是函数范围的函数,并且不能在函数本身之外访问(由于函数的性质)表达)。
2) 2)
incrementbytwo(number)
that expects a number as a argument incrementbytwo(number)
的函数语句,该语句需要一个数字作为参数increment
(hence is a function expression. The function expression uses the same signature as the function statement - therefore takes a single argument that it passes into the function. increment
(因此是一个函数表达式。函数表达式使用与函数语句相同的签名 - 因此采用它传递给函数的单个参数。 3) There isn't one. 3) 没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.