Home >Web Front-end >JS Tutorial >How can we simulate private methods in JavaScript for enhanced encapsulation?
While public methods provide external access to class functionalities, private methods offer isolated operations within the class. JavaScript doesn't natively support private methods, but innovative approaches can mimic this concept.
Consider the following scenario:
<code class="javascript">function Restaurant() {} Restaurant.prototype.buy_food = function(){ // something here } Restaurant.prototype.use_restroom = function(){ // something here }</code>
In this example, both buy_food and use_restroom are public methods accessible outside the class. How can we introduce a private method that only these public methods can call?
JavaScript lacks true private methods, but it allows us to create local functions within class constructors that are not accessible externally. Here's how:
<code class="javascript">function Restaurant() { var myPrivateVar; var private_stuff = function() { // Only visible inside Restaurant() myPrivateVar = "I can set this here!"; } 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>
In this example, private_stuff is a local function within the Restaurant constructor. It's not part of the prototype and is only accessible by the use_restroom and buy_food methods.
This approach maintains the desired separation between public and "private" methods while allowing the latter to operate seamlessly within the class.
The above is the detailed content of How can we simulate private methods in JavaScript for enhanced encapsulation?. For more information, please follow other related articles on the PHP Chinese website!