JavaScript private methods

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

    In these situations when you have a public API, and you would like private and public methods/properties, I always use the Module Pattern. This pattern was made popular within the YUI library, and the details can be found here:

    http://yuiblog.com/blog/2007/06/12/module-pattern/

    It is really straightforward, and easy for other developers to comprehend. For a simple example:

    var MYLIB = function() {  
        var aPrivateProperty = true;
        var aPrivateMethod = function() {
            // some code here...
        };
        return {
            aPublicMethod : function() {
                aPrivateMethod(); // okay
                // some code here...
            },
            aPublicProperty : true
        };  
    }();
    
    MYLIB.aPrivateMethod() // not okay
    MYLIB.aPublicMethod() // okay
    

提交回复
热议问题