Home > Article > Web Front-end > How to Achieve Encapsulation with Private Methods in JavaScript?
Private Methods in JavaScript
Encapsulating data and methods within a class is a fundamental principle in object-oriented programming. In JavaScript, however, defining private methods within a class can be challenging.
Creating a Public Method
To create a public method in JavaScript, we typically use the prototype property:
<code class="javascript">function Restaurant() {} Restaurant.prototype.buy_food = function(){ // something here }; Restaurant.prototype.use_restroom = function(){ // something here };</code>
Users can access these methods as follows:
<code class="javascript">var restaurant = new Restaurant(); restaurant.buy_food(); restaurant.use_restroom();</code>
Defining Private Methods
To create a private method that is only accessible to other methods within the class, we can define it outside of the prototype:
<code class="javascript">function Restaurant() { var private_stuff = function() { // Only visible inside Restaurant() // Do something }; this.use_restroom = function() { // use_restroom is visible to all private_stuff(); }; this.buy_food = function() { // buy_food is visible to all private_stuff(); }; }</code>
Limitations
This approach has a downside: private methods cannot be part of the prototype. This means they cannot be accessed directly from an instance of the class:
<code class="javascript">var r = new Restaurant(); r.private_stuff(); // This will not work</code>
Therefore, private methods can only be called by public methods within the same class. While this may provide some level of encapsulation, it is not as robust as true private methods found in other programming languages.
The above is the detailed content of How to Achieve Encapsulation with Private Methods in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!