JavaScript private methods

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

    You have to put a closure around your actual constructor-function, where you can define your private methods. To 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) :

    var Restaurant = (function(){
        var private_buy_food = function(that){
            that.data.soldFood = true;
        }
        var private_take_a_shit = function(){
            this.data.isdirty = true;   
        }
        // New Closure
        function restaurant()
        {
            this.data = {
                isdirty : false,
                soldFood: false,
            };
        }
    
        restaurant.prototype.buy_food = function()
        {
           private_buy_food(this);
        }
        restaurant.prototype.use_restroom = function()
        {
           private_take_a_shit.call(this);
        }
        return restaurant;
    })()
    
    // TEST:
    
    var McDonalds = new Restaurant();
    McDonalds.buy_food();
    McDonalds.use_restroom();
    console.log(McDonalds);
    console.log(McDonalds.__proto__);
    

提交回复
热议问题