Home > Article > Web Front-end > What are the application scenarios of closures?
Closure application scenarios include: 1. SetTimeout call using function reference; 2. Replace global variables with a small scope; 3. Public methods with access to private variables and private functions.
Local variables inside the function cannot be accessed from outside the function, but functions inside the function can access local variables within this function, so external access to the function is achieved through closures Local variables inside the function. However, it can easily cause memory leaks and should be used with caution.
Usage scenarios of closures:
1], setTimeout call using function reference method
The first parameter of setTimeout is usually a The function to be executed, the second parameter is a delay time.
If a piece of code wants to be called through setTimeout, then it needs to pass a reference to a function object as the first parameter, but the reference to this function object cannot provide parameters for the object that will be delayed. At this time, you can call another function to return a call to the internal function, and pass the reference of the internal function object to the setTimeout function. The parameters required when the internal function is executed are passed to it when calling the external function. setTimeout is used when executing the internal function. There is no need to pass parameters because the internal function can still protect against forgery of the parameters provided when the external function is called.
2】, small scope instead of global variables
3】, privileged method to access private variables ?
Privileged methods: public methods that have access to private variables and private functions
Private variables include:
1), local variables
2) Parameters of the function
3) Other functions (closures) defined inside the function
Two are defined in the constructor of the above code Privileged methods: getName(), setName(), these two methods can be accessed through the object, and both have access to the private variable name, but there is no method to access name outside the Person constructor. Since these two methods are defined inside the function, they can be accessed through the scope chain as closures.
Recommended tutorial: "JS Tutorial"
The above is the detailed content of What are the application scenarios of closures?. For more information, please follow other related articles on the PHP Chinese website!