In the previous articles, I have introduced the closure of js. This article briefly introduces the closure paradigm in js. So what is the closure paradigm? First, let's review the concept of closure. Closure is a bridge between external functions and internal functions. By Returning functions, external functions can
In the previous articles, I have introduced the closure of js. This article briefly introduces the closure paradigm in js.
So what is the closure paradigm?
First, let's review the concept of closure. Closure is a bridge between external functions and internal functions. By Returning functions, external functions can access internal functions.
Some data. That is to say, the closure can make the data inside the function private or public.
The paradigm is actually an anonymous function in js. It looks like this. Below is an anonymous function, that is, a closure.
(function(){ })()
Since it is a function, you can also pass parameters. The parameter passing in an anonymous function looks like the following:
(function(b){ })(a)
Here, a is a real parameter, and B is a form parameter. We can also pass multiple parameters.
As we have discussed above, closures can achieve data privatization and public clouds. How can the paradigm solve this problem? Here is a simple example:
(Function (window) {var name = 'function'; function getFunctions () {return {fb: fb, // public function fc: fc };} function fa () {console.info ('fa ');} function fb () {console.info ('fb');} function fc () {console.info ('fc ');} function fd () {console.info ('fd ');} window. getFunctions = getFunctions () ;}) (window); console.info (window. getFunctions. fb (); console.info (window. getFunctions. fc (); console.info (window. getFunctions. fa (); console.info (window. getFunctions. fd ());
As shown in the preceding js, there is an anonymous function with the parameter window. In the anonymous function, getFunctions () is assigned to an attribute of window, so that getFunctions () is public, so how can we control other functions to be public or private? In getFunctions (), we return a json object containing two methods, which is equivalent to exposing the two functions in getFunctions.