This article introduces the block-level scope, private variables and module mode in JavaScript in detail, which is very helpful for learning JavaScript.
This article introduces the block-level scope, private variables and module mode in JavaScript in detail. I won’t go into too much nonsense. The details are as follows:
1. Block-level scope (Private scope), is often used outside functions in the global scope, thereby limiting the addition of too many variables and functions to the global scope.
1 2 3 4 5 6 |
|
1 2 3 4 5 6 7 8 |
|
2. Private variables: Any variables defined in a function can be considered private variables, because these variables cannot be accessed outside the function.
Privileged methods: Public methods that have access to private variables and private functions are called privileged methods.
2.1) Define privileged methods in the constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
The disadvantage of the constructor pattern is that the same set of new methods will be created for each instance.
2.2) Static private variables to implement privileged methods
In the private scope, first define private variables and private functions, and then define the constructor and its public methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
3. Module pattern: Singletons can be enhanced by adding private variables and privileged methods.
If you must create an object and initialize it with some data, while also exposing some methods that can access these private data, you can use the module pattern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
jsInstance of executing a function after the code is delayed for a certain period of time
Detailed explanation of how to use JS hash to create a single-page web application
JS simple implementation of floating windows
The above is the detailed content of In-depth understanding of block-level scope, private variables and module mode in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!