<p>To make a JavaScript class with a public method I'd do something like:</p>

<pre><code>function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something here
}

Restaurant.prototype.use_restroom = function(){
   // something here
}
</code></pre>

<p>That way users of my class can:</p>

<pre><code>var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
</code></pre>

<p>How do I create a private method that can be called by the <code>buy_food</code> and <code>use_restroom</code> methods but not externally by users of the class?</p>

<p>In other words, I want my method implementation to be able to do:</p>

<pre><code>Restaurant.prototype.use_restroom = function() {
   this.private_stuff();
}
</code></pre>

<p>But this shouldn't work:</p>

<pre><code>var r = new Restaurant();
r.private_stuff();
</code></pre>

<p>How do I define <code>private_stuff</code> as a private method so both of these hold true?</p>

<p>I've read <a href="http://javascript.crockford.com/private.html" rel="noreferrer">Doug Crockford's writeup</a> a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.</p>

[{'answer_id': 55637, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 10, 'selected': True, 'text': '<p>You can do it, but the downside is that it can\'t be part of the prototype:</p>\n\n<pre><code>function Restaurant() {\n    var myPrivateVar;\n\n    var private_stuff = function() {  // Only visible inside Restaurant()\n        myPrivateVar = "I can set this here!";\n    }\n\n    this.use_restroom = function() {  // use_restroom is visible to all\n        private_stuff();\n    }\n\n    this.buy_food = function() {   // buy_food is visible to all\n        private_stuff();\n    }\n}\n</code></pre>\n'}, {'answer_id': 55638, 'author': 'georgebrock', 'author_id': 5168, 'author_profile': 'https://Stackoverflow.com/users/5168', 'pm_score': 7, 'selected': False, 'text': '<p>You can simulate private methods like this:</p>\n\n<pre><code>function Restaurant() {\n}\n\nRestaurant.prototype = (function() {\n    var private_stuff = function() {\n        // Private code here\n    };\n\n    return {\n\n        constructor:Restaurant,\n\n        use_restroom:function() {\n            private_stuff();\n        }\n\n    };\n})();\n\nvar r = new Restaurant();\n\n// This will work:\nr.use_restroom();\n\n// This will cause an error:\nr.private_stuff();\n</code></pre>\n\n<p>More information on this technique here: <a href="http://webreflection.blogspot.com/2008/04/natural-javascript-private-methods.html" rel="noreferrer">http://webreflection.blogspot.com/2008/04/natural-javascript-private-methods.html</a></p>\n'}, {'answer_id': 55696, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>In these situations when you have a public API, and you would like private and public methods/properties, I always use the Module Pattern. This pattern was made popular within the YUI library, and the details can be found here:</p>\n\n<p><a href="http://yuiblog.com/blog/2007/06/12/module-pattern/" rel="noreferrer">http://yuiblog.com/blog/2007/06/12/module-pattern/</a></p>\n\n<p>It is really straightforward, and easy for other developers to comprehend. For a simple example:</p>\n\n<pre><code>var MYLIB = function() {  \n    var aPrivateProperty = true;\n    var aPrivateMethod = function() {\n        // some code here...\n    };\n    return {\n        aPublicMethod : function() {\n            aPrivateMethod(); // okay\n            // some code here...\n        },\n        aPublicProperty : true\n    };  \n}();\n\nMYLIB.aPrivateMethod() // not okay\nMYLIB.aPublicMethod() // okay\n</code></pre>\n'}, {'answer_id': 55739, 'author': 'Daniel Stockman', 'author_id': 5707, 'author_profile': 'https://Stackoverflow.com/users/5707', 'pm_score': 2, 'selected': False, 'text': '<p>The apotheosis of the Module Pattern: <a href="http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/" rel="nofollow noreferrer" title="from Chris Heilemann, naturally">The Revealing Module Pattern</a></p>\n\n<p>A neat little extension to a very robust pattern.</p>\n'}, {'answer_id': 63016, 'author': 'Kelly', 'author_id': 7157, 'author_profile': 'https://Stackoverflow.com/users/7157', 'pm_score': 3, 'selected': False, 'text': '<p>All of this closure will cost you.  Make sure you test the speed implications especially in IE. You will find you are better off with a naming convention. There are still a lot of corporate web users out there that are forced to use IE6...</p>\n'}, {'answer_id': 148219, 'author': 'domgblackwell', 'author_id': 16954, 'author_profile': 'https://Stackoverflow.com/users/16954', 'pm_score': 2, 'selected': False, 'text': '<p>If you want the full range of public and private functions with the ability for public functions to access private functions, layout code for an object like this:</p>\n\n<pre><code>function MyObject(arg1, arg2, ...) {\n  //constructor code using constructor arguments...\n  //create/access public variables as \n  // this.var1 = foo;\n\n  //private variables\n\n  var v1;\n  var v2;\n\n  //private functions\n  function privateOne() {\n  }\n\n  function privateTwon() {\n  }\n\n  //public functions\n\n  MyObject.prototype.publicOne = function () {\n  };\n\n  MyObject.prototype.publicTwo = function () {\n  };\n}\n</code></pre>\n'}, {'answer_id': 1361654, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>I conjured up this: EDIT: Actually, someone has linked to a identical solution. Duh!</p>\n\n<pre><code>var Car = function() {\n}\n\nCar.prototype = (function() {\n    var hotWire = function() {\n        // Private code *with* access to public properties through 'this'\n        alert( this.drive() ); // Alerts 'Vroom!'\n    }\n\n    return {\n        steal: function() {\n            hotWire.call( this ); // Call a private method\n        },\n        drive: function() {\n            return 'Vroom!';\n        }\n    };\n})();\n\nvar getAwayVechile = new Car();\n\nhotWire(); // Not allowed\ngetAwayVechile.hotWire(); // Not allowed\ngetAwayVechile.steal(); // Alerts 'Vroom!'\n</code></pre>\n"}, {'answer_id': 5703989, 'author': 'David', 'author_id': 713524, 'author_profile': 'https://Stackoverflow.com/users/713524', 'pm_score': 2, 'selected': False, 'text': '<pre><code>var TestClass = function( ) {\n\n    var privateProperty = 42;\n\n    function privateMethod( ) {\n        alert( "privateMethod, " + privateProperty );\n    }\n\n    this.public = {\n        constructor: TestClass,\n\n        publicProperty: 88,\n        publicMethod: function( ) {\n            alert( "publicMethod" );\n            privateMethod( );\n        }\n    };\n};\nTestClass.prototype = new TestClass( ).public;\n\n\nvar myTestClass = new TestClass( );\n\nalert( myTestClass.publicProperty );\nmyTestClass.publicMethod( );\n\nalert( myTestClass.privateMethod || "no privateMethod" );\n</code></pre>\n\n<p>Similar to georgebrock but a little less verbose (IMHO)\nAny problems with doing it this way? (I haven\'t seen it anywhere)</p>\n\n<p>edit: I realised this is kinda useless since every independent instantiation has its own copy of the public methods, thus undermining the use of the prototype.</p>\n'}, {'answer_id': 6169955, 'author': 'Dooma', 'author_id': 765125, 'author_profile': 'https://Stackoverflow.com/users/765125', 'pm_score': 0, 'selected': False, 'text': '<p>Private functions cannot access the public variables using module pattern</p>\n'}, {'answer_id': 9288441, 'author': 'Sarath', 'author_id': 353241, 'author_profile': 'https://Stackoverflow.com/users/353241', 'pm_score': 4, 'selected': False, 'text': '<p>Here is the class which I created to understand what Douglas Crockford\'s has suggested in his site <a href="http://javascript.crockford.com/private.html">Private Members in JavaScript</a></p>\n\n<pre class="lang-js prettyprint-override"><code>function Employee(id, name) { //Constructor\n    //Public member variables\n    this.id = id;\n    this.name = name;\n    //Private member variables\n    var fName;\n    var lName;\n    var that = this;\n    //By convention, we create a private variable \'that\'. This is used to     \n    //make the object available to the private methods. \n\n    //Private function\n    function setFName(pfname) {\n        fName = pfname;\n        alert(\'setFName called\');\n    }\n    //Privileged function\n    this.setLName = function (plName, pfname) {\n        lName = plName;  //Has access to private variables\n        setFName(pfname); //Has access to private function\n        alert(\'setLName called \' + this.id); //Has access to member variables\n    }\n    //Another privileged member has access to both member variables and private variables\n    //Note access of this.dataOfBirth created by public member setDateOfBirth\n    this.toString = function () {\n        return \'toString called \' + this.id + \' \' + this.name + \' \' + fName + \' \' + lName + \' \' + this.dataOfBirth; \n    }\n}\n//Public function has access to member variable and can create on too but does not have access to private variable\nEmployee.prototype.setDateOfBirth = function (dob) {\n    alert(\'setDateOfBirth called \' + this.id);\n    this.dataOfBirth = dob;   //Creates new public member note this is accessed by toString\n    //alert(fName); //Does not have access to private member\n}\n$(document).ready()\n{\n    var employee = new Employee(5, \'Shyam\'); //Create a new object and initialize it with constructor\n    employee.setLName(\'Bhaskar\', \'Ram\');  //Call privileged function\n    employee.setDateOfBirth(\'1/1/2000\');  //Call public function\n    employee.id = 9;                     //Set up member value\n    //employee.setFName(\'Ram\');  //can not call Private Privileged method\n    alert(employee.toString());  //See the changed object\n\n}\n</code></pre>\n'}, {'answer_id': 13327997, 'author': 'mark', 'author_id': 1753943, 'author_profile': 'https://Stackoverflow.com/users/1753943', 'pm_score': 0, 'selected': False, 'text': '<p>Since everybody was posting here his own code, I\'m gonna do that too...</p>\n\n<p>I like Crockford because he introduced real object oriented patterns in Javascript. But he also came up with a new misunderstanding, the "that" one.</p>\n\n<p>So why is he using "that = this"? It has nothing to do with private functions at all. It has to do with inner functions! </p>\n\n<p>Because according to Crockford this is buggy code: </p>\n\n<pre><code>Function Foo( ) {\n    this.bar = 0; \n    var foobar=function( ) {\n        alert(this.bar);\n    }\n} \n</code></pre>\n\n<p>So he suggested doing this:</p>\n\n<pre><code>Function Foo( ) {\n    this.bar = 0;\n    that = this; \n    var foobar=function( ) {\n        alert(that.bar);\n    }\n}\n</code></pre>\n\n<p>So as I said, I\'m quite sure that Crockford was wrong his explanation about that and this (but his code is certainly correct). Or was he just fooling the Javascript world, to know who is copying his code? I dunno...I\'m no browser geek ;D</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Ah, that\'s what is all about: <a href="https://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript">What does &#39;var that = this;&#39; mean in JavaScript?</a></p>\n\n<p>So Crockie was really wrong with his explanation....but right with his code, so he\'s still a great guy. :))</p>\n'}, {'answer_id': 15721313, 'author': 'Andreas Dyballa', 'author_id': 1636136, 'author_profile': 'https://Stackoverflow.com/users/1636136', 'pm_score': 0, 'selected': False, 'text': '<p>In general I added the private Object _ temporarily to the object.\nYou have to open the privacy exlipcitly in the "Power-constructor" for the method.\nIf you call the method from the prototype, you will\nbe able to overwrite the prototype-method</p>\n\n<ul>\n<li><p>Make a public method accessible in the "Power-constructor": (ctx is the object context)</p>\n\n<pre><code>ctx.test = GD.Fabric.open(\'test\', GD.Test.prototype, ctx, _); // is a private object\n</code></pre></li>\n<li><p>Now I have this openPrivacy:</p>\n\n<pre><code>GD.Fabric.openPrivacy = function(func, clss, ctx, _) {\n    return function() {\n        ctx._ = _;\n        var res = clss[func].apply(ctx, arguments);\n        ctx._ = null;\n        return res;\n    };\n};\n</code></pre></li>\n</ul>\n'}, {'answer_id': 16605660, 'author': 'Flex Elektro Deimling', 'author_id': 530335, 'author_profile': 'https://Stackoverflow.com/users/530335', 'pm_score': 0, 'selected': False, 'text': '<p>You have to put a closure around your actual constructor-function, where you can define your private methods.\nTo change data of the instances through these private methods, you have to give them "this" with them, either as an function argument or by calling this function with .apply(this) :</p>\n\n<pre><code>var Restaurant = (function(){\n    var private_buy_food = function(that){\n        that.data.soldFood = true;\n    }\n    var private_take_a_shit = function(){\n        this.data.isdirty = true;   \n    }\n    // New Closure\n    function restaurant()\n    {\n        this.data = {\n            isdirty : false,\n            soldFood: false,\n        };\n    }\n\n    restaurant.prototype.buy_food = function()\n    {\n       private_buy_food(this);\n    }\n    restaurant.prototype.use_restroom = function()\n    {\n       private_take_a_shit.call(this);\n    }\n    return restaurant;\n})()\n\n// TEST:\n\nvar McDonalds = new Restaurant();\nMcDonalds.buy_food();\nMcDonalds.use_restroom();\nconsole.log(McDonalds);\nconsole.log(McDonalds.__proto__);\n</code></pre>\n'}, {'answer_id': 18222581, 'author': 'iimos', 'author_id': 502860, 'author_profile': 'https://Stackoverflow.com/users/502860', 'pm_score': 4, 'selected': False, 'text': "<p>I think such questions come up again and again because of the lack of understanding of the  closures. Сlosures is most important thing in JS. Every JS programmer have to feel the essence of it.</p>\n\n<p><strong>1.</strong> First of all we need to make separate scope (closure).</p>\n\n<pre><code>function () {\n\n}\n</code></pre>\n\n<p><strong>2.</strong> In this area, we can do whatever we want. And no one will know about it.</p>\n\n<pre><code>function () {\n    var name,\n        secretSkills = {\n            pizza: function () { return new Pizza() },\n            sushi: function () { return new Sushi() }\n        }\n\n    function Restaurant(_name) {\n        name = _name\n    }\n    Restaurant.prototype.getFood = function (name) {\n        return name in secretSkills ? secretSkills[name]() : null\n    }\n}\n</code></pre>\n\n<p><strong>3.</strong> For the world to know about our restaurant class, \nwe have to return it from the closure.</p>\n\n<pre><code>var Restaurant = (function () {\n    // Restaurant definition\n    return Restaurant\n})()\n</code></pre>\n\n<p><strong>4.</strong> At the end, we have:</p>\n\n<pre><code>var Restaurant = (function () {\n    var name,\n        secretSkills = {\n            pizza: function () { return new Pizza() },\n            sushi: function () { return new Sushi() }\n        }\n\n    function Restaurant(_name) {\n        name = _name\n    }\n    Restaurant.prototype.getFood = function (name) {\n        return name in secretSkills ? secretSkills[name]() : null\n    }\n    return Restaurant\n})()\n</code></pre>\n\n<p><strong>5.</strong> Also, this approach has potential for inheritance and templating</p>\n\n<pre><code>// Abstract class\nfunction AbstractRestaurant(skills) {\n    var name\n    function Restaurant(_name) {\n        name = _name\n    }\n    Restaurant.prototype.getFood = function (name) {\n        return skills &amp;&amp; name in skills ? skills[name]() : null\n    }\n    return Restaurant\n}\n\n// Concrete classes\nSushiRestaurant = AbstractRestaurant({ \n    sushi: function() { return new Sushi() } \n})\n\nPizzaRestaurant = AbstractRestaurant({ \n    pizza: function() { return new Pizza() } \n})\n\nvar r1 = new SushiRestaurant('Yo! Sushi'),\n    r2 = new PizzaRestaurant('Dominos Pizza')\n\nr1.getFood('sushi')\nr2.getFood('pizza')\n</code></pre>\n\n<p>I hope this helps someone better understand this subject</p>\n"}, {'answer_id': 18239876, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>This is what I worked out:</p>\n\n<p>Needs one class of sugar code that <a href="https://github.com/najamelan/TidBits_Javascript_OoJs" rel="nofollow">you can find here</a>. Also supports protected, inheritance, virtual, static stuff...</p>\n\n<pre><code>;( function class_Restaurant( namespace )\n{\n    \'use strict\';\n\n    if( namespace[ "Restaurant" ] ) return    // protect against double inclusions\n\n        namespace.Restaurant = Restaurant\n    var Static               = TidBits.OoJs.setupClass( namespace, "Restaurant" )\n\n\n    // constructor\n    //\n    function Restaurant()\n    {\n        this.toilets = 3\n\n        this.Private( private_stuff )\n\n        return this.Public( buy_food, use_restroom )\n    }\n\n    function private_stuff(){ console.log( "There are", this.toilets, "toilets available") }\n\n    function buy_food     (){ return "food"        }\n    function use_restroom (){ this.private_stuff() }\n\n})( window )\n\n\nvar chinese = new Restaurant\n\nconsole.log( chinese.buy_food()      );  // output: food\nconsole.log( chinese.use_restroom()  );  // output: There are 3 toilets available\nconsole.log( chinese.toilets         );  // output: undefined\nconsole.log( chinese.private_stuff() );  // output: undefined\n\n// and throws: TypeError: Object #&lt;Restaurant&gt; has no method \'private_stuff\'\n</code></pre>\n'}, {'answer_id': 19695554, 'author': 'Evan Leis', 'author_id': 981337, 'author_profile': 'https://Stackoverflow.com/users/981337', 'pm_score': 2, 'selected': False, 'text': '<p>What about this?</p>\n\n<pre><code>var Restaurant = (function() {\n\n var _id = 0;\n var privateVars = [];\n\n function Restaurant(name) {\n     this.id = ++_id;\n     this.name = name;\n     privateVars[this.id] = {\n         cooked: []\n     };\n }\n\n Restaurant.prototype.cook = function (food) {\n     privateVars[this.id].cooked.push(food);\n }\n\n return Restaurant;\n\n})();\n</code></pre>\n\n<p>Private variable lookup is impossible outside of the scope of the immediate function.\nThere is no duplication of functions, saving memory.</p>\n\n<p>The downside is that the lookup of private variables is clunky <code>privateVars[this.id].cooked</code> is ridiculous to type. There is also an extra "id" variable.</p>\n'}, {'answer_id': 20500648, 'author': 'snowkid', 'author_id': 3087829, 'author_profile': 'https://Stackoverflow.com/users/3087829', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Class({  \n    Namespace:ABC,  \n    Name:"ClassL2",  \n    Bases:[ABC.ClassTop],  \n    Private:{  \n        m_var:2  \n    },  \n    Protected:{  \n        proval:2,  \n        fight:Property(function(){  \n            this.m_var--;  \n            console.log("ClassL2::fight (m_var)" +this.m_var);  \n        },[Property.Type.Virtual])  \n    },  \n    Public:{  \n        Fight:function(){  \n            console.log("ClassL2::Fight (m_var)"+this.m_var);  \n            this.fight();  \n        }  \n    }  \n});  \n</code></pre>\n\n<p><a href="https://github.com/nooning/JSClass" rel="nofollow">https://github.com/nooning/JSClass</a></p>\n'}, {'answer_id': 21167136, 'author': 'Trem', 'author_id': 732236, 'author_profile': 'https://Stackoverflow.com/users/732236', 'pm_score': 0, 'selected': False, 'text': '<p>I have created a new tool to allow you to have true private methods on the prototype\n<a href="https://github.com/TremayneChrist/ProtectJS" rel="nofollow">https://github.com/TremayneChrist/ProtectJS</a></p>\n\n<p>Example:</p>\n\n<pre><code>var MyObject = (function () {\n\n  // Create the object\n  function MyObject() {}\n\n  // Add methods to the prototype\n  MyObject.prototype = {\n\n    // This is our public method\n    public: function () {\n      console.log(\'PUBLIC method has been called\');\n    },\n\n    // This is our private method, using (_)\n    _private: function () {\n      console.log(\'PRIVATE method has been called\');\n    }\n  }\n\n  return protect(MyObject);\n\n})();\n\n// Create an instance of the object\nvar mo = new MyObject();\n\n// Call its methods\nmo.public(); // Pass\nmo._private(); // Fail\n</code></pre>\n'}, {'answer_id': 25172901, 'author': 'Yves M.', 'author_id': 1480391, 'author_profile': 'https://Stackoverflow.com/users/1480391', 'pm_score': 8, 'selected': False, 'text': '<h1>Using self invoking function and call</h1>\n<p>JavaScript uses <a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="noreferrer">prototypes</a> and does\'t have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.</p>\n<p>Wikipedia quote:</p>\n<blockquote>\n<p>Unlike many object-oriented languages, there is no distinction between\na function definition and a method definition. Rather, the distinction\noccurs during function calling; when a function is called as a method\nof an object, the function\'s local this keyword is bound to that\nobject for that invocation.</p>\n</blockquote>\n<p>Solution using a <a href="http://en.wikipedia.org/wiki/Immediately-invoked_function_expression" rel="noreferrer">self invoking function</a> and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" rel="noreferrer">call function</a> to call the private &quot;method&quot; :</p>\n<pre class="lang-js prettyprint-override"><code>var MyObject = (function () {\n    \n  // Constructor\n  function MyObject(foo) {\n    this._foo = foo;\n  }\n\n  function privateFun(prefix) {\n    return prefix + this._foo;\n  }\n    \n  MyObject.prototype.publicFun = function () {\n    return privateFun.call(this, &quot;&gt;&gt;&quot;);\n  }\n    \n  return MyObject;\n\n}());\n</code></pre>\n<pre class="lang-js prettyprint-override"><code>var myObject = new MyObject(&quot;bar&quot;);\nmyObject.publicFun();      // Returns &quot;&gt;&gt;bar&quot;\nmyObject.privateFun(&quot;&gt;&gt;&quot;); // ReferenceError: private is not defined\n</code></pre>\n<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" rel="noreferrer">call function</a> allows us to call the private function with the appropriate context (<code>this</code>).</p>\n<h1>Simpler with Node.js</h1>\n<p>If you are using <a href="http://nodejs.org/" rel="noreferrer">Node.js</a>, you don\'t need the <a href="http://en.wikipedia.org/wiki/Immediately-invoked_function_expression" rel="noreferrer">IIFE</a> because you can take advantage of the <a href="http://nodejs.org/api/modules.html" rel="noreferrer">module loading system</a>:</p>\n<pre class="lang-js prettyprint-override"><code>function MyObject(foo) {\n  this._foo = foo;\n}\n    \nfunction privateFun(prefix) {\n  return prefix + this._foo;\n}\n\nMyObject.prototype.publicFun = function () {\n  return privateFun.call(this, &quot;&gt;&gt;&quot;);\n}\n    \nmodule.exports= MyObject;\n</code></pre>\n<p>Load the file:</p>\n<pre class="lang-js prettyprint-override"><code>var MyObject = require(&quot;./MyObject&quot;);\n    \nvar myObject = new MyObject(&quot;bar&quot;);\nmyObject.publicFun();      // Returns &quot;&gt;&gt;bar&quot;\nmyObject.privateFun(&quot;&gt;&gt;&quot;); // ReferenceError: private is not defined\n</code></pre>\n<h1>(new!) Native private methods in future JavaScript versions</h1>\n<p>TC39 <a href="https://github.com/tc39/proposal-private-methods" rel="noreferrer">private methods and getter/setters for JavaScript classes</a> proposal is stage 3. That means any time soon, JavaScript will implement private methods natively!</p>\n<p>Note that <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields" rel="noreferrer">JavaScript private class fields</a> already exists in modern JavaScript versions.</p>\n<p>Here is an example of how it is used:</p>\n<pre class="lang-js prettyprint-override"><code>class MyObject {\n\n  // Private field\n  #foo;\n    \n  constructor(foo) {\n    this.#foo = foo;\n  }\n\n  #privateFun(prefix) {\n   return prefix + this.#foo;\n  }\n    \n  publicFun() {\n    return this.#privateFun(&quot;&gt;&gt;&quot;);\n  }\n\n}\n</code></pre>\n<p>You may need a <a href="https://babeljs.io" rel="noreferrer">JavaScript transpiler/compiler</a> to run this code on old JavaScript engines.</p>\n<p>PS: If you wonder why the <code>#</code> prefix, <a href="https://github.com/tc39/proposal-private-fields/issues/14" rel="noreferrer">read this</a>.</p>\n<h1>(deprecated) ES7 with the Bind Operator</h1>\n<p>Warning: The bind operator TC39 proposition is near dead <a href="https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822" rel="noreferrer">https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822</a></p>\n<p>The bind operator <code>::</code> is an ECMAScript <a href="https://github.com/zenparsing/es-function-bind" rel="noreferrer">proposal</a> and is <a href="https://babeljs.io/blog/2015/05/14/function-bind" rel="noreferrer">implemented in Babel</a> (<a href="https://babeljs.io/docs/plugins/preset-stage-0/" rel="noreferrer">stage 0</a>).</p>\n<pre><code>export default class MyObject {\n  constructor (foo) {\n    this._foo = foo;\n  }\n\n  publicFun () {\n    return this::privateFun(&quot;&gt;&gt;&quot;);\n  }\n}\n\nfunction privateFun (prefix) {\n  return prefix + this._foo;\n}\n</code></pre>\n'}, {'answer_id': 25366378, 'author': 'Fozi', 'author_id': 168683, 'author_profile': 'https://Stackoverflow.com/users/168683', 'pm_score': 2, 'selected': False, 'text': '<p>Take any of the solutions that follow Crockford\'s <em>private</em> or <em>priviledged</em> pattern. For example:</p>\n\n<pre><code>function Foo(x) {\n    var y = 5;\n    var bar = function() {\n        return y * x;\n    };\n\n    this.public = function(z) {\n        return bar() + x * z;\n    };\n}\n</code></pre>\n\n<p>In any case where the attacker has no "execute" right on the JS context he has no way of accessing any "public" or "private" fields or methods. In case the attacker does have that access he can execute this one-liner:</p>\n\n<pre><code>eval("Foo = " + Foo.toString().replace(\n    /{/, "{ this.eval = function(code) { return eval(code); }; "\n));\n</code></pre>\n\n<p>Note that the above code is generic to all constructor-type-privacy. It will fail with some of the solutions here but it should be clear that pretty much all of the closure based solutions can be broken like this with different <code>replace()</code> parameters. </p>\n\n<p>After this is executed any object created with <code>new Foo()</code> is going to have an <code>eval</code> method which can be called to return or change values or methods defined in the constructor\'s closure, e.g.:</p>\n\n<pre><code>f = new Foo(99);\nf.eval("x");\nf.eval("y");\nf.eval("x = 8");\n</code></pre>\n\n<p>The only problem I can see with this that it won\'t work for cases where there is only one instance and it\'s created on load. But then there is no reason to actually define a prototype and in that case the attacker can simply recreate the object instead of the constructor as long as he has a way of passing the same parameters (e.g. they are constant or calculated from available values).</p>\n\n<p><strong>In my opinion, this pretty much makes Crockford\'s solution useless.</strong> Since the "privacy" is easily broken the downsides of his solution (reduced readability &amp; maintainability, decreased performance, increased memory) makes the "no privacy" prototype based method the better choice. </p>\n\n<p>I do usually use leading underscores to mark <code>__private</code> and <code>_protected</code> methods and fields (Perl style), but the idea of having privacy in JavaScript just shows how it\'s a misunderstood language. </p>\n\n<p><strong>Therefore I disagree with <a href="http://crockford.com/javascript/private.html" rel="nofollow noreferrer">Crockford</a></strong> except for his first sentence.</p>\n\n<p><strong>So how do you get real privacy in JS?</strong> Put everything that is required to be private on the server side and use JS to do AJAX calls.</p>\n'}, {'answer_id': 27396880, 'author': 'low_rents', 'author_id': 3391783, 'author_profile': 'https://Stackoverflow.com/users/3391783', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s what i enjoyed the most so far regarding private/public methods/members and instantiation in javascript:</p>\n\n<p>here is the article: <a href="http://www.sefol.com/?p=1090" rel="nofollow">http://www.sefol.com/?p=1090</a></p>\n\n<p>and here is the example:</p>\n\n<pre><code>var Person = (function () {\n\n    //Immediately returns an anonymous function which builds our modules \n    return function (name, location) {\n\n        alert("createPerson called with " + name);\n\n        var localPrivateVar = name;\n\n        var localPublicVar = "A public variable";\n\n        var localPublicFunction = function () {\n            alert("PUBLIC Func called, private var is :" + localPrivateVar)\n        };\n\n        var localPrivateFunction = function () {\n            alert("PRIVATE Func called ")\n        };\n\n        var setName = function (name) {\n\n            localPrivateVar = name;\n\n        }\n\n        return {\n\n            publicVar: localPublicVar,\n\n            location: location,\n\n            publicFunction: localPublicFunction,\n\n            setName: setName\n\n        }\n\n    }\n})();\n\n\n//Request a Person instance - should print "createPerson called with ben"\nvar x = Person("ben", "germany");\n\n//Request a Person instance - should print "createPerson called with candide"\nvar y = Person("candide", "belgium");\n\n//Prints "ben"\nx.publicFunction();\n\n//Prints "candide"\ny.publicFunction();\n\n//Now call a public function which sets the value of a private variable in the x instance\nx.setName("Ben 2");\n\n//Shouldn\'t have changed this : prints "candide"\ny.publicFunction();\n\n//Should have changed this : prints "Ben 2"\nx.publicFunction();\n</code></pre>\n\n<p>JSFiddle: <a href="http://jsfiddle.net/northkildonan/kopj3dt3/1/" rel="nofollow">http://jsfiddle.net/northkildonan/kopj3dt3/1/</a></p>\n'}, {'answer_id': 28190815, 'author': 'Maxim Balaganskiy', 'author_id': 944182, 'author_profile': 'https://Stackoverflow.com/users/944182', 'pm_score': 0, 'selected': False, 'text': '<p>I know it\'s a bit too late but how about this?</p>\n\n<pre><code>var obj = function(){\n    var pr = "private";\n    var prt = Object.getPrototypeOf(this);\n    if(!prt.hasOwnProperty("showPrivate")){\n        prt.showPrivate = function(){\n            console.log(pr);\n        }\n    }    \n}\n\nvar i = new obj();\ni.showPrivate();\nconsole.log(i.hasOwnProperty("pr"));\n</code></pre>\n'}, {'answer_id': 28279952, 'author': 'James', 'author_id': 1185191, 'author_profile': 'https://Stackoverflow.com/users/1185191', 'pm_score': 2, 'selected': False, 'text': "<p>The module pattern is right in most cases. But if you have thousands of instances, classes save memory. If saving memory is a concern and your objects contain a small amount of private data, but have a lot of public functions, then you'll want all public functions to live in the .prototype to save memory.</p>\n\n<p>This is what I came up with:</p>\n\n<pre><code>var MyClass = (function () {\n    var secret = {}; // You can only getPriv() if you know this\n    function MyClass() {\n        var that = this, priv = {\n            foo: 0 // ... and other private values\n        };\n        that.getPriv = function (proof) {\n            return (proof === secret) &amp;&amp; priv;\n        };\n    }\n    MyClass.prototype.inc = function () {\n        var priv = this.getPriv(secret);\n        priv.foo += 1;\n        return priv.foo;\n    };\n    return MyClass;\n}());\nvar x = new MyClass();\nx.inc(); // 1\nx.inc(); // 2\n</code></pre>\n\n<p>The object <code>priv</code> contains private properties. It is accessible through the public function <code>getPriv()</code>, but this function returns <code>false</code> unless you pass it the <code>secret</code>, and this is only known inside the main closure.</p>\n"}, {'answer_id': 31042160, 'author': 'Abdennour TOUMI', 'author_id': 747579, 'author_profile': 'https://Stackoverflow.com/users/747579', 'pm_score': 2, 'selected': False, 'text': '<p>Wrap all code in Anonymous Function: Then , all functions will be private ,ONLY  functions attached  to <code>window</code> object : </p>\n\n<pre><code>(function(w,nameSpacePrivate){\n     w.Person=function(name){\n         this.name=name;   \n         return this;\n     };\n\n     w.Person.prototype.profilePublic=function(){\n          return nameSpacePrivate.profile.call(this);\n     };  \n\n     nameSpacePrivate.profile=function(){\n       return \'My name is \'+this.name;\n     };\n\n})(window,{});\n</code></pre>\n\n<p>Use this : </p>\n\n<pre><code>  var abdennour=new Person(\'Abdennour\');\n  abdennour.profilePublic();\n</code></pre>\n\n<h1><a href="https://jsfiddle.net/abdennour/8nzgm64u/" rel="nofollow">FIDDLE</a></h1>\n'}, {'answer_id': 37141668, 'author': 'thegunmaster', 'author_id': 3080469, 'author_profile': 'https://Stackoverflow.com/users/3080469', 'pm_score': 0, 'selected': False, 'text': '<p>There are many answers on this question already, but nothing fitted my needs. So i came up with my own solution, I hope it is usefull for someone:</p>\n\n<pre><code>function calledPrivate(){\n    var stack = new Error().stack.toString().split("\\n");\n    function getClass(line){\n        var i = line.indexOf(" ");\n        var i2 = line.indexOf(".");\n        return line.substring(i,i2);\n    }\n    return getClass(stack[2])==getClass(stack[3]);\n}\n\nclass Obj{\n    privateMethode(){\n        if(calledPrivate()){\n            console.log("your code goes here");\n        }\n    }\n    publicMethode(){\n        this.privateMethode();\n    }\n}\n\nvar obj = new Obj();\nobj.publicMethode(); //logs "your code goes here"\nobj.privateMethode(); //does nothing\n</code></pre>\n\n<p>As you can see this system works when using this type of classes in javascript. As far as I figured out none of the methods commented above did.</p>\n'}, {'answer_id': 44423507, 'author': 'John Slegers', 'author_id': 1946501, 'author_profile': 'https://Stackoverflow.com/users/1946501', 'pm_score': 3, 'selected': False, 'text': '<p>Personally, I prefer the following pattern for creating classes in JavaScript :</p>\n<pre><code>var myClass = (function() {\n    // Private class properties go here\n\n    var blueprint = function() {\n        // Private instance properties go here\n        ...\n    };\n\n    blueprint.prototype = { \n        // Public class properties go here\n        ...\n    };\n\n    return  {\n         // Public class properties go here\n        create : function() { return new blueprint(); }\n        ...\n    };\n})();\n</code></pre>\n<p>As you can see, it allows you to define both class properties and instance properties, each of which can be public and private.</p>\n<hr />\n<h3>Demo</h3>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var Restaurant = function() {\n    var totalfoodcount = 0;        // Private class property\n    var totalrestroomcount  = 0;   // Private class property\n    \n    var Restaurant = function(name){\n        var foodcount = 0;         // Private instance property\n        var restroomcount  = 0;    // Private instance property\n        \n        this.name = name\n        \n        this.incrementFoodCount = function() {\n            foodcount++;\n            totalfoodcount++;\n            this.printStatus();\n        };\n        this.incrementRestroomCount = function() {\n            restroomcount++;\n            totalrestroomcount++;\n            this.printStatus();\n        };\n        this.getRestroomCount = function() {\n            return restroomcount;\n        },\n        this.getFoodCount = function() {\n            return foodcount;\n        }\n    };\n   \n    Restaurant.prototype = {\n        name : \'\',\n        buy_food : function(){\n           this.incrementFoodCount();\n        },\n        use_restroom : function(){\n           this.incrementRestroomCount();\n        },\n        getTotalRestroomCount : function() {\n            return totalrestroomcount;\n        },\n        getTotalFoodCount : function() {\n            return totalfoodcount;\n        },\n        printStatus : function() {\n           document.body.innerHTML\n               += \'&lt;h3&gt;Buying food at \'+this.name+\'&lt;/h3&gt;\'\n               + \'&lt;ul&gt;\' \n               + \'&lt;li&gt;Restroom count at \' + this.name + \' : \'+ this.getRestroomCount() + \'&lt;/li&gt;\'\n               + \'&lt;li&gt;Food count at \' + this.name + \' : \' + this.getFoodCount() + \'&lt;/li&gt;\'\n               + \'&lt;li&gt;Total restroom count : \'+ this.getTotalRestroomCount() + \'&lt;/li&gt;\'\n               + \'&lt;li&gt;Total food count : \'+ this.getTotalFoodCount() + \'&lt;/li&gt;\'\n               + \'&lt;/ul&gt;\';\n        }\n    };\n\n    return  { // Singleton public properties\n        create : function(name) {\n            return new Restaurant(name);\n        },\n        printStatus : function() {\n          document.body.innerHTML\n              += \'&lt;hr /&gt;\'\n              + \'&lt;h3&gt;Overview&lt;/h3&gt;\'\n              + \'&lt;ul&gt;\' \n              + \'&lt;li&gt;Total restroom count : \'+ Restaurant.prototype.getTotalRestroomCount() + \'&lt;/li&gt;\'\n              + \'&lt;li&gt;Total food count : \'+ Restaurant.prototype.getTotalFoodCount() + \'&lt;/li&gt;\'\n              + \'&lt;/ul&gt;\'\n              + \'&lt;hr /&gt;\';\n        }\n    };\n}();\n\nvar Wendys = Restaurant.create("Wendy\'s");\nvar McDonalds = Restaurant.create("McDonald\'s");\nvar KFC = Restaurant.create("KFC");\nvar BurgerKing = Restaurant.create("Burger King");\n\nRestaurant.printStatus();\n\nWendys.buy_food();\nWendys.use_restroom();\nKFC.use_restroom();\nKFC.use_restroom();\nWendys.use_restroom();\nMcDonalds.buy_food();\nBurgerKing.buy_food();\n\nRestaurant.printStatus();\n\nBurgerKing.buy_food();\nWendys.use_restroom();\nMcDonalds.buy_food();\nKFC.buy_food();\nWendys.buy_food();\nBurgerKing.buy_food();\nMcDonalds.buy_food();\n\nRestaurant.printStatus();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>See also <a href="https://jsfiddle.net/0yL21mr6/1/" rel="noreferrer"><strong>this Fiddle</strong></a>.</p>\n'}, {'answer_id': 48833952, 'author': 'rich remer', 'author_id': 1078314, 'author_profile': 'https://Stackoverflow.com/users/1078314', 'pm_score': 1, 'selected': False, 'text': "<p>I prefer to store private data in an associated <code>WeakMap</code>.  This allows you to keep your public methods on the prototype where they belong.  This seems to be the most efficient way to handle this problem for large numbers of objects.</p>\n\n<pre><code>const data = new WeakMap();\n\nfunction Foo(value) {\n    data.set(this, {value});\n}\n\n// public method accessing private value\nFoo.prototype.accessValue = function() {\n    return data.get(this).value;\n}\n\n// private 'method' accessing private value\nfunction accessValue(foo) {\n    return data.get(foo).value;\n}\n\nexport {Foo};\n</code></pre>\n"}, {'answer_id': 51470058, 'author': 'prograhammer', 'author_id': 1110941, 'author_profile': 'https://Stackoverflow.com/users/1110941', 'pm_score': 3, 'selected': False, 'text': '<p>Don\'t be so verbose. It\'s Javascript. Use a <strong>Naming Convention</strong>.</p>\n\n<p>After years of working in es6 classes, I recently started work on an es5 project (using requireJS which is already very verbose-looking). I\'ve been over and over all the strategies mentioned here and it all basically boils down to <strong>use a naming convention</strong>:</p>\n\n<ol>\n<li>Javascript doesn\'t have scope keywords like <code>private</code>. Other developers entering Javascript will know this upfront. Therefore, a simple naming convention is more than sufficient. A simple naming convention of prefixing with an underscore solves the problem of both private properties and private methods. </li>\n<li>Let\'s take advantage of the Prototype for speed reasons, but lets not get anymore verbose than that. Let\'s try to keep the es5 "class" looking as closely to what we might expect in other backend  languages (and treat every file as a class, even if we don\'t need to return an instance).</li>\n<li>Let\'s demonstrate with a more realistic module situation (we\'ll use old es5 and old requireJs).</li>\n</ol>\n\n<p><strong>my-tooltip.js</strong>  </p>\n\n<pre><code>    define([\n        \'tooltip\'\n    ],\n    function(\n        tooltip\n    ){\n\n        function MyTooltip() {\n            // Later, if needed, we can remove the underscore on some\n            // of these (make public) and allow clients of our class\n            // to set them.\n            this._selector = "#my-tooltip"\n            this._template = \'Hello from inside my tooltip!\';\n            this._initTooltip();\n        }\n\n        MyTooltip.prototype = {\n            constructor: MyTooltip,\n\n            _initTooltip: function () {\n                new tooltip.tooltip(this._selector, {\n                    content: this._template,\n                    closeOnClick: true,\n                    closeButton: true\n                });\n            }\n        }\n\n        return {\n            init: function init() {\n               new MyTooltip();  // &lt;-- Our constructor adds our tooltip to the DOM so not much we need to do after instantiation.\n            }\n\n            // You could instead return a new instantiation, \n            // if later you do more with this class.\n            /* \n            create: function create() {\n               return new MyTooltip();\n            }\n            */\n        }\n    });\n</code></pre>\n'}, {'answer_id': 59474509, 'author': 'D-Marc', 'author_id': 3822526, 'author_profile': 'https://Stackoverflow.com/users/3822526', 'pm_score': 4, 'selected': False, 'text': '<h1><strong>ES12 Private Methods</strong></h1>\n<p>You can do this now with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields" rel="nofollow noreferrer">es12 private methods</a>. You just need to add a <code>#</code> before the method name.</p>\n<pre><code>class ClassWithPrivateMethod {\n  #privateMethod() {\n    return \'hello world\';\n  }\n\n  getPrivateMessage() {\n    return #privateMethod();\n  }\n}\n</code></pre>\n'}, {'answer_id': 63722178, 'author': 'Daniel Shlomo', 'author_id': 1510406, 'author_profile': 'https://Stackoverflow.com/users/1510406', 'pm_score': 0, 'selected': False, 'text': '<p>An ugly solution but it works:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function Class(cb) {\n    const self = {};\n\n    const constructor = (fn) =&gt; {\n        func = fn;    \n    };\n\n    const addPrivate = (fnName, obj) =&gt; {\n        self[fnName] = obj;\n    }\n\n    const addPublic = (fnName, obj) =&gt; {\n        this[fnName] = obj;\n        self[fnName] = obj;\n        func.prototype[fnName] = obj;\n    }\n    \n    cb(constructor, addPrivate, addPublic, self);\n    return func;\n}\n\nconst test = new Class((constructor, private, public, self) =&gt; {\n    constructor(function (test) {\n        console.log(test)\n    });\n    public(\'test\', \'yay\');\n    private(\'qwe\', \'nay\');\n    private(\'no\', () =&gt; {\n        return \'hello\'\n    })\n    public(\'asd\', () =&gt; {\n        return \'this is public\'\n    })\n    public(\'hello\', () =&gt; {\n        return self.qwe + self.no() + self.asd()\n    })\n})\nconst asd = new test(\'qweqwe\');\nconsole.log(asd.hello());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 64504570, 'author': 't_dom93', 'author_id': 6774916, 'author_profile': 'https://Stackoverflow.com/users/6774916', 'pm_score': 4, 'selected': False, 'text': '<h2 id="es2021-es12-private-methods">ES2021 / ES12 - Private Methods</h2>\n<p>Private method names start with a hash <code>#</code> prefix and can be accessed <strong>only</strong> inside the class where it is defined.</p>\n<pre><code>class Restaurant {\n\n  // private method\n  #private_stuff() {\n    console.log(&quot;private stuff&quot;);\n  }\n\n  // public method\n  buy_food() {\n    this.#private_stuff();\n  }\n\n};\n\nconst restaurant = new Restaurant();\nrestaurant.buy_food(); // &quot;private stuff&quot;;\nrestaurant.private_stuff(); // Uncaught TypeError: restaurant.private_stuff is not a function\n</code></pre>\n'}, {'answer_id': 65552423, 'author': 'Redu', 'author_id': 4543207, 'author_profile': 'https://Stackoverflow.com/users/4543207', 'pm_score': 0, 'selected': False, 'text': '<p>Old question but this is a rather simple task that can be solved <strong>properly</strong> with core JS... without the Class abstraction of ES6. In fact as far as i can tell, the Class abstraction do not even solve this problem.</p>\n<p>We can do this job both with the good old constructor function or even better with <code>Object.create()</code>. Lets go with the constructor first. This will essentially be a similar solution to <a href="https://stackoverflow.com/a/55638/4543207">georgebrock\'s answer</a> which is criticised because all restaurants created by the <code>Restaurant</code> constructor will have the same private methods. I will try to overcome that limitation.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function restaurantFactory(name,menu){\n\n  function Restaurant(name){\n    this.name = name;\n  }\n\n  function prototypeFactory(menu){\n    // This is a private function\n    function calculateBill(item){\n      return menu[item] || 0;\n    }\n    // This is the prototype to be\n    return { constructor: Restaurant\n           , askBill    : function(...items){\n                            var cost = items.reduce((total,item) =&gt; total + calculateBill(item) ,0)\n                            return "Thank you for dining at " + this.name + ". Total is: " + cost + "\\n"\n                          }\n           , callWaiter : function(){\n                            return "I have just called the waiter at " + this.name + "\\n";\n                          }\n           }\n  }\n\n  Restaurant.prototype = prototypeFactory(menu);\n\n  return new Restaurant(name,menu);\n}\n\nvar menu = { water: 1\n           , coke : 2\n           , beer : 3\n           , beef : 15\n           , rice : 2\n           },\n    name = "Silver Scooop",\n    rest = restaurantFactory(name,menu);\n\nconsole.log(rest.callWaiter());\nconsole.log(rest.askBill("beer", "beef"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Now obviously we can not access <code>menu</code> from outside but we may easily rename the <code>name</code> property of a restaurant.</p>\n<p>This can also be done with <code>Object.create()</code> in which case we skip the constructor function and simply do like <code> var rest = Object.create(prototypeFactory(menu))</code> and add the name property to the <code>rest</code> object afterwards like <code>rest.name = name</code>.</p>\n'}, {'answer_id': 67235368, 'author': 'yorg', 'author_id': 3225970, 'author_profile': 'https://Stackoverflow.com/users/3225970', 'pm_score': 0, 'selected': False, 'text': "<p>I know it is an old topic but i tried to find a way to preserve the code 'simplicity' for maintainability purposes and keep a light memory load. It came with this pattern. Hope it helps.</p>\n<pre><code>const PublicClass=function(priv,pub,ro){\n    let _priv=new PrivateClass(priv,pub,ro);\n    ['publicMethod'].forEach(k=&gt;this[k]=(...args)=&gt;_priv[k](...args));\n    ['publicVar'].forEach(k=&gt;Object.defineProperty(this,k,{get:()=&gt;_priv[k],set:v=&gt;_priv[k]=v}));\n    ['readOnlyVar'].forEach(k=&gt;Object.defineProperty(this,k,{get:()=&gt;_priv[k]}));\n};\n\nclass PrivateClass{\n    constructor(priv,pub,ro){\n        this.privateVar=priv;\n        this.publicVar=pub;\n        this.readOnlyVar=ro;\n    }\n    publicMethod(arg1,arg2){\n        return this.privateMethod(arg1,arg2);\n    }\n    privateMethod(arg1,arg2){\n        return arg1+''+arg2;\n    }\n}\n// in node;\nmodule.exports=PublicClass;\n// in browser;\nconst PublicClass=(function(){\n    // code here\n    return PublicClass;\n})();\n</code></pre>\n<p>Same principle for old browsers :</p>\n<pre><code>var PublicClass=function(priv,pub,ro){\n    var scope=this;\n    var _priv=new PrivateClass(priv,pub,ro);\n    ['publicMethod'].forEach(function(k){\n        scope[k]=function(){return _priv[k].apply(_priv,arguments)};\n    });\n    ['publicVar'].forEach(function(k){\n        Object.defineProperty(scope,k,{get:function(){return _priv[k]},set:function(v){_priv[k]=v}});\n    });\n    ['readOnlyVar'].forEach(function(k){\n        Object.defineProperty(scope,k,{get:function(){return _priv[k]}});\n    });\n};\n\nvar PrivateClass=function(priv,pub,ro){\n    this.privateVar=priv;\n    this.publicVar=pub;\n    this.readOnlyVar=ro;\n};\nPrivateClass.prototype.publicMethod=function(arg1,arg2){\n    return this.privateMethod(arg1,arg2);\n};\nPrivateClass.prototype.privateMethod=function(arg1,arg2){\n    return arg1+''+arg2;\n};\n</code></pre>\n<hr />\n<p>To lighten public class verbosity and load, apply this pattern to a constructor :</p>\n<pre><code>const AbstractPublicClass=function(instanciate,inherit){\n    let _priv=instanciate();\n    inherit.methods?.forEach(k=&gt;this[k]=(...args)=&gt;_priv[k](...args));\n    inherit.vars?.forEach(k=&gt;Object.defineProperty(this,k,{get:()=&gt;_priv[k],set:v=&gt;_priv[k]=v}));\n    inherit.readonly?.forEach(k=&gt;Object.defineProperty(this,k,{get:()=&gt;_priv[k]}));\n};\n\nAbstractPublicClass.static=function(_pub,_priv,inherit){\n    inherit.methods?.forEach(k=&gt;_pub[k]=(...args)=&gt;_priv[k](...args));\n    inherit.vars?.forEach(k=&gt;Object.defineProperty(_pub,k,{get:()=&gt;_priv[k],set:v=&gt;_priv[k]=v}));\n    inherit.readonly?.forEach(k=&gt;Object.defineProperty(_pub,k,{get:()=&gt;_priv[k]}));\n};\n</code></pre>\n<p>Use :</p>\n<pre><code>// PrivateClass ...\nPrivateClass.staticVar='zog';\nPrivateClass.staticMethod=function(){return 'hello '+this.staticVar;};\n\n\nconst PublicClass=function(priv,pub,ro){\n    AbstractPublicClass.apply(this,[()=&gt;new PrivateClass(priv,pub,ro),{\n        methods:['publicMethod'],\n        vars:['publicVar'],\n        readonly:['readOnlyVar']\n    }]);\n};\nAbstractPublicClass.static(PublicClass,PrivateClass,{\n    methods:['staticMethod'],\n    vars:['staticVar']\n});\n</code></pre>\n<hr />\n<p>PS : The default (negligeable most of the time) in this approach is it can take a tiny computing load compared to a full public. But as long as you dont use it whith highly solicited classes that should be ok.</p>\n"}, {'answer_id': 68978023, 'author': 'denik1981', 'author_id': 13578650, 'author_profile': 'https://Stackoverflow.com/users/13578650', 'pm_score': 1, 'selected': False, 'text': '<p><strong>2021 HERE!</strong></p>\n<p>This polyfill effectively hides your private properties and methods returning <strong>undefined</strong> when you try to read your private property and a <strong>TypeError</strong> when you try to execute your private method thus effectively making them both <strong>PRIVATE</strong> to the outside but giving you access to them by using your public methods.</p>\n<p>If you check it you will see it is very easy to implement. For the most part you don\'t need to do anything quirky like using Proxy objects, underscore functions (_myprivate), getters or setters. None of that. The only thing required is to place in your constructor that like snippet of code that is aimed to let you expose your public interface to the outside world.</p>\n<pre><code>((self) =&gt; ({\n      pubProp: self.pubProp,\n      // More public properties to export HERE\n      // ...\n      pubMethod: self.pubMethod.bind(self)\n      // More public mehods to export HERE\n      // Be sure bind each of them to self!!!\n      // ... \n }))(self);\n</code></pre>\n<p>The above code is where the magic happens. It is an IIFE that returns an object with just the properties and methods you want to exposed and bound to the context of the object that was first instantiated.</p>\n<p>You can still access your hidden properties and methods but only through your public methods just the way OOP should do.<br />\nConsider that part of the code as your <strong>module.exports</strong></p>\n<p>BTW this is without using the latest ES6 &quot;<strong>#</strong>&quot; addition to the language.</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>\'use strict\';\n\nclass MyClass {\n  constructor(pubProp) {\n    let self = this;\n    self.pubProp = pubProp;\n    self.privProp = "I\'m a private property!";\n    return ((self) =&gt; ({\n      pubProp: self.pubProp,\n      // More public properties to export HERE\n      // ...\n      pubMethod: self.pubMethod.bind(self)\n      // More public mehods to export HERE\n      // Be sure to bind each of them to self!!!\n      // ... \n    }))(self);\n  }\n\n  pubMethod() {\n    console.log("I\'m a public method!");\n    console.log(this.pubProp);\n\n    return this.privMethod();\n  }\n\n  privMethod() {\n    console.log("I\'m a private method!");\n  return this.privProp\n  }\n}\n\nconst myObj = new MyClass("I\'m a public property!");\nconsole.log("***DUMPING MY NEW INSTANCE***");\nconsole.dir(myObj);\nconsole.log("");\nconsole.log("***TESTING ACCESS TO PUBLIC PROPERTIES***");\nconsole.log(myObj.pubProp);\nconsole.log("");\nconsole.log("***TESTING ACCESS TO PRIVATE PROPERTIES***");\nconsole.log(myObj.privProp);\nconsole.log("");\nconsole.log("***TESTING ACCESS TO PUBLIC METHODS***");\nconsole.log("1. pubMethod access pubProp ");\nconsole.log("2. pubMethod calls privMethod");\nconsole.log("3. privMethod access privProp");\nconsole.log("")\nconsole.log(myObj.pubMethod());\nconsole.log("");\nconsole.log("***TESTING ACCESS TO PRIVATE METHODS***");\nconsole.log(myObj.privMethod());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href="https://git.io/JEPGi" rel="nofollow noreferrer">Check my gist</a></p>\n'}]
['https://Stackoverflow.com/questions/55611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3284/']