JavaScript private methods

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

    var TestClass = function( ) {
    
        var privateProperty = 42;
    
        function privateMethod( ) {
            alert( "privateMethod, " + privateProperty );
        }
    
        this.public = {
            constructor: TestClass,
    
            publicProperty: 88,
            publicMethod: function( ) {
                alert( "publicMethod" );
                privateMethod( );
            }
        };
    };
    TestClass.prototype = new TestClass( ).public;
    
    
    var myTestClass = new TestClass( );
    
    alert( myTestClass.publicProperty );
    myTestClass.publicMethod( );
    
    alert( myTestClass.privateMethod || "no privateMethod" );
    

    Similar to georgebrock but a little less verbose (IMHO) Any problems with doing it this way? (I haven't seen it anywhere)

    edit: I realised this is kinda useless since every independent instantiation has its own copy of the public methods, thus undermining the use of the prototype.

提交回复
热议问题