JavaScript private methods

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

    This is what I worked out:

    Needs one class of sugar code that you can find here. Also supports protected, inheritance, virtual, static stuff...

    ;( function class_Restaurant( namespace )
    {
        'use strict';
    
        if( namespace[ "Restaurant" ] ) return    // protect against double inclusions
    
            namespace.Restaurant = Restaurant
        var Static               = TidBits.OoJs.setupClass( namespace, "Restaurant" )
    
    
        // constructor
        //
        function Restaurant()
        {
            this.toilets = 3
    
            this.Private( private_stuff )
    
            return this.Public( buy_food, use_restroom )
        }
    
        function private_stuff(){ console.log( "There are", this.toilets, "toilets available") }
    
        function buy_food     (){ return "food"        }
        function use_restroom (){ this.private_stuff() }
    
    })( window )
    
    
    var chinese = new Restaurant
    
    console.log( chinese.buy_food()      );  // output: food
    console.log( chinese.use_restroom()  );  // output: There are 3 toilets available
    console.log( chinese.toilets         );  // output: undefined
    console.log( chinese.private_stuff() );  // output: undefined
    
    // and throws: TypeError: Object # has no method 'private_stuff'
    

提交回复
热议问题