JavaScript private methods

前端 未结 30 1860
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:16

To make a JavaScript class with a public method I\'d do something like:

function Restaurant() {}

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


        
30条回答
  •  孤城傲影
    2020-11-22 09:03

    I have created a new tool to allow you to have true private methods on the prototype https://github.com/TremayneChrist/ProtectJS

    Example:

    var MyObject = (function () {
    
      // Create the object
      function MyObject() {}
    
      // Add methods to the prototype
      MyObject.prototype = {
    
        // This is our public method
        public: function () {
          console.log('PUBLIC method has been called');
        },
    
        // This is our private method, using (_)
        _private: function () {
          console.log('PRIVATE method has been called');
        }
      }
    
      return protect(MyObject);
    
    })();
    
    // Create an instance of the object
    var mo = new MyObject();
    
    // Call its methods
    mo.public(); // Pass
    mo._private(); // Fail
    

提交回复
热议问题