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

前端 未结 2 1013
傲寒
傲寒 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 09:58

    When implementing the module pattern, how do private functions access the private properties of the module?

    The properties are in scope, so they "just do"

    Doesn't work.

    Yes, it does.

    _privateIncrement doesn't have access to the module's scope.

    Yes, it does.

    See live example of the following:

    var module = (function(){
        // private property
        var number = 0;
    
        // global method
        _privateIncrement = function(){
            number++;
        };
    
        // public api
        return {
            // OK
            getNumber: function(){
                 return number;   
            },
            // OK
            incrNumber: function(){
                 number++;  
            },
            // Does work!
            privateIncrNumber: function(){
                _privateIncrement();
            }
        };
    })();
    
    // Show default value
    document.body.innerHTML += (module.getNumber());
    // Increment
    module.privateIncrNumber();
    // Show new value
    document.body.innerHTML += (module.getNumber());
    // Increment (since _privateIncrement was defined as a global!)
    _privateIncrement();
    // Show new value
    document.body.innerHTML += (module.getNumber());
    
    // Output: 012
    

提交回复
热议问题