JavaScript private methods

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

    You can simulate private methods like this:

    function Restaurant() {
    }
    
    Restaurant.prototype = (function() {
        var private_stuff = function() {
            // Private code here
        };
    
        return {
    
            constructor:Restaurant,
    
            use_restroom:function() {
                private_stuff();
            }
    
        };
    })();
    
    var r = new Restaurant();
    
    // This will work:
    r.use_restroom();
    
    // This will cause an error:
    r.private_stuff();
    

    More information on this technique here: http://webreflection.blogspot.com/2008/04/natural-javascript-private-methods.html

提交回复
热议问题