JavaScript private methods

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

    I conjured up this: EDIT: Actually, someone has linked to a identical solution. Duh!

    var Car = function() {
    }
    
    Car.prototype = (function() {
        var hotWire = function() {
            // Private code *with* access to public properties through 'this'
            alert( this.drive() ); // Alerts 'Vroom!'
        }
    
        return {
            steal: function() {
                hotWire.call( this ); // Call a private method
            },
            drive: function() {
                return 'Vroom!';
            }
        };
    })();
    
    var getAwayVechile = new Car();
    
    hotWire(); // Not allowed
    getAwayVechile.hotWire(); // Not allowed
    getAwayVechile.steal(); // Alerts 'Vroom!'
    

提交回复
热议问题