JavaScript module pattern: How do private methods access module's scope?

前端 未结 2 1081
傲寒
傲寒 2021-02-04 09:07

When implementing the module pattern, how do private functions access the private properties of the module? I haven\'t seen any examples where developers do this. Is there any r

2条回答
  •  面向向阳花
    2021-02-04 10:01

    One alternative to have private methods with access to the this is by using the call or apply methods.

    function Restaurant()
    {
        this.mongoose = 'beans';
        this.freedom = {bear:'love',a:'12'};
    
        var myPrivateVar;
    
        var private_stuff = function()   // Only visible inside Restaurant()
        {
            myPrivateVar = "I can set this here!";
            this.mongoose = 12;
        }
    
        this.use_restroom = function()   // use_restroom is visible to all
        {
            private_stuff();
        }
    
        this.buy_food = function()    // buy_food is visible to all
        {
            private_stuff();
        }
    
        private_stuff.call(this);
    }
    
    var bobbys = new Restaurant();
    

    Of course you would move the use_restroom and buy_food to a prototype and private_stuff outside of the constructor if you were planning on having multiple instances of this object.

提交回复
热议问题