Home >Web Front-end >JS Tutorial >Closure principles and examples

Closure principles and examples

不言
不言forward
2018-10-18 14:03:163621browse

Closure principles and examples

This article brings you a detailed introduction to the closure principle and examples. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Closure

After the function is called, an execution environment and scope chain will be created. The function will be released after it is executed.

After the closure function is executed, the current active variable will be retained in the inner function scope chain, so the inner function can access the outer variable.

Closure principles and examples

(Related tutorial recommendations: js tutorial)

Example 1

What is the printed result?

Closure principles and examples

Example 2

What is the printed result?

Closure principles and examples

The variables declared by var are only Function scope and global scope, the i variable created in this loop will be raised to the top of the function, so the value of the i variable printed by the function is 10

Example 3

The printed result What is it?

Closure principles and examples

#The variable declared by let has block-level scope. Each time the i variable is looped, it is a new i variable, so the myArr array stores Different numbers

Example four

What is the printed result?

Closure principles and examples

This just creates and executes 10 functions, each function An i variable is passed to the parameter j, j stores the variable value, and then prints it out, so the result is 0~9

For more programming related content, please pay attention to php Chinese website Introduction to Programming column!

The above is the detailed content of Closure principles and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete