JavaScript private methods

前端 未结 30 1864
-上瘾入骨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:56

    What about this?

    var Restaurant = (function() {
    
     var _id = 0;
     var privateVars = [];
    
     function Restaurant(name) {
         this.id = ++_id;
         this.name = name;
         privateVars[this.id] = {
             cooked: []
         };
     }
    
     Restaurant.prototype.cook = function (food) {
         privateVars[this.id].cooked.push(food);
     }
    
     return Restaurant;
    
    })();
    

    Private variable lookup is impossible outside of the scope of the immediate function. There is no duplication of functions, saving memory.

    The downside is that the lookup of private variables is clunky privateVars[this.id].cooked is ridiculous to type. There is also an extra "id" variable.

提交回复
热议问题