Defining Private Methods in JavaScript
Creating classes in JavaScript provides a clear separation of functions and data. Public methods are easily accessible, but how do you define private methods that can only be accessed by other methods within the class?
To implement private methods in JavaScript, you can take the following approach:
1. Declare Private Variables:
Define private variables within the constructor function to store data that should be accessible only within the class.
2. Create Private Functions:
Define private functions outside of the class prototype. These functions are only accessible within the scope of the constructor function.
3. Call Private Functions from Public Methods:
Public methods can call private functions to access private data and perform specific tasks. However, private functions cannot be called directly from outside the class.
For example:
<code class="javascript">function Restaurant() { var privateVar; // Private variable var privateFunction = function() { // Private function privateVar = "Private data"; } this.publicMethod1 = function() { // Public method privateFunction(); // Can call private function } this.publicMethod2 = function() { // Public method privateFunction(); // Can call private function } }</code>
In this example, privateFunction is a private function that sets the value of the private variable privateVar. Public methods publicMethod1 and publicMethod2 can call privateFunction to access private data. However, external code cannot call privateFunction directly.
Limitations:
This approach has one main limitation: private methods cannot be part of the class prototype. This означает, что ты cannot define them using object literal shorthand notation.
The above is the detailed content of How do you define private methods in JavaScript classes?. For more information, please follow other related articles on the PHP Chinese website!