JavaScript private methods

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

    I think such questions come up again and again because of the lack of understanding of the closures. Сlosures is most important thing in JS. Every JS programmer have to feel the essence of it.

    1. First of all we need to make separate scope (closure).

    function () {
    
    }
    

    2. In this area, we can do whatever we want. And no one will know about it.

    function () {
        var name,
            secretSkills = {
                pizza: function () { return new Pizza() },
                sushi: function () { return new Sushi() }
            }
    
        function Restaurant(_name) {
            name = _name
        }
        Restaurant.prototype.getFood = function (name) {
            return name in secretSkills ? secretSkills[name]() : null
        }
    }
    

    3. For the world to know about our restaurant class, we have to return it from the closure.

    var Restaurant = (function () {
        // Restaurant definition
        return Restaurant
    })()
    

    4. At the end, we have:

    var Restaurant = (function () {
        var name,
            secretSkills = {
                pizza: function () { return new Pizza() },
                sushi: function () { return new Sushi() }
            }
    
        function Restaurant(_name) {
            name = _name
        }
        Restaurant.prototype.getFood = function (name) {
            return name in secretSkills ? secretSkills[name]() : null
        }
        return Restaurant
    })()
    

    5. Also, this approach has potential for inheritance and templating

    // Abstract class
    function AbstractRestaurant(skills) {
        var name
        function Restaurant(_name) {
            name = _name
        }
        Restaurant.prototype.getFood = function (name) {
            return skills && name in skills ? skills[name]() : null
        }
        return Restaurant
    }
    
    // Concrete classes
    SushiRestaurant = AbstractRestaurant({ 
        sushi: function() { return new Sushi() } 
    })
    
    PizzaRestaurant = AbstractRestaurant({ 
        pizza: function() { return new Pizza() } 
    })
    
    var r1 = new SushiRestaurant('Yo! Sushi'),
        r2 = new PizzaRestaurant('Dominos Pizza')
    
    r1.getFood('sushi')
    r2.getFood('pizza')
    

    I hope this helps someone better understand this subject

提交回复
热议问题