JavaScript private methods

前端 未结 30 1490
-上瘾入骨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 08:54

    You can do it, but the downside is that it can't be part of the prototype:

    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();
        }
    }
    

提交回复
热议问题