JavaScript 模块模式 : How do private methods access module's scope?

标签 javascript module-pattern

在实现模块模式时,私有(private)函数如何访问模块的私有(private)属性?我还没有看到开发人员这样做的任何例子。有什么理由不这样做吗?

var module = (function(){
    // private property
    var number = 0;

    // private method
    _privateIncrement = function(){
        // how do I access private properties here?
        number++;
    };

    // public api
    return {
        // OK
        getNumber: function(){
             return number;   
        },
        // OK
        incrNumber: function(){
             number++;  
        },
        // Doesn't work. _privateIncrement doesn't have
        // access to the module's scope.
        privateIncrNumber: function(){
            _privateIncrement();
        }
    };
})();

最佳答案

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

属性在范围内,所以它们“只是做”

Doesn't work.

是的,确实如此。

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

是的,确实如此。

参见 live example以下:

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

关于JavaScript 模块模式 : How do private methods access module's scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8579885/

相关文章:

javascript - Clipboardjs 将div的html内容复制到剪贴板

javascript - 如何避免手动缓存返回错误的请求?

javascript - 如何将 JavaScript 代码库划分为模块?

javascript - 排序和过滤器不起作用 - Ngtable

javascript - 在 Angular 应用程序中,通过 chrome 开发工具检查元素时,为什么我看不到纯 html?

JavaScript 使用模块模式创建类

javascript - 从内部扩展命名空间模块

javascript - JS模块模式覆盖函数

javascript - 在您的网站上载自定义字体

javascript - 在 Angular 中如何让代码在回调函数之后运行?