When we pass in a function, there are times when we don't need to explicitly define the function and pass in directly
Anonymous FunctionsMore convenient.
In Python, there is a limited amount of support for anonymous functions . As an example of the map () function, when calculating f (x) =x2, in addition to defining an F (x) function, you can also pass in the anonymous function directly:
>>> list (map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) [1, 4, 9, 16, 25, 36, 49, 64, 81]
The comparison shows that the anonymous function lambda x:x * x is actually:
def f (x): return x * x
The keyword lambda represents an anonymous function, and the x preceding the colon represents the function parameter.
There is a limit to the anonymous function, that is, there can be only one expression, without writing return, the return value is the result of that expression.
There is a benefit to using anonymous functions because the function does not have a name and does not have to worry about function name collisions. In addition, the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to invoke the function:
>>> f = Lambda x:x * x>>> f<function <lambda> at 0x101c6ef28>>>> F (5) 25
Similarly, anonymous functions can be returned as return values, such as:
def build (x, y): return lambda:x * x + y * y
Encapsulation details, which increase security and controllability, are often used outside the function in the global scope to limit the addition of too many variables and functions to the global scope.
Using a block-level scope in a global scope reduces the problem of blocking memory, because there is no reference to the anonymous function, and as long as the function is executed, its scope chain can be destroyed immediately.
Impersonation block-level (private) Scope:
function box () { for (Var i=0;i<5;i++) { //block-level scope (JS none) } var I//Even if re-declared, it will not affect the previous value alert (i);//5} Box ();