JavaScript模块模式:私有方法如何访问模块的范围? [英] JavaScript module pattern: How do private methods access module's scope?

查看:88
本文介绍了JavaScript模块模式:私有方法如何访问模块的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 reason not to?

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?

属性在范围内,所以他们只做

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


不起作用。

Doesn't work.

是的,确实如此。


_privateIncrement 无法访问模块的范围。

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

是的,确实如此。

参见实例以下内容:

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模块模式:私有方法如何访问模块的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆