了解一个基本的模块模式的私有和公共功能

Understanding a basic modular patterns private and public functions

本文关键字:模式 功能 模块 了解 一个      更新时间:2023-09-26

我刚才看了一个简单的模块模式演示代码,看看吧:

// Global module
var myModule = (function ( jQ, _ ) {
    function privateMethod1(){
        jQ(".container").html("test");
    }
    function privateMethod2(){
      console.log( _.min([10, 5, 100, 2, 1000]) );
    }
    return{
        publicMethod: function(){
            privateMethod1();
        }
    };
// Pull in jQuery and Underscore
})( jQuery, _ );
myModule.publicMethod();

代码很简单,我不明白的是publicMethod的需求是什么?为什么privateMethod1privateMethod2不可访问?我知道privateMethod1privateMethod2是经典的js函数,publicMethod更多的是一个分配给保持函数的变量。

privateMethod1()privateMethod2()是在模块函数包装器内声明的局部函数。因此,它们只能在该函数包装器中可见和可调用。它们不能从模块包装器外部访问。

这与函数内部的局部变量相同。

function someFunc() {
    // a function declared inside another function is ONLY available
    // inside that function
    function localFunc() {
        // do something
    }
    // this is just like a local variable which is only available within
    // the scope of the function itself
    var myVariable = 2;
}
// can't call localFunc here - this will be an error
// because it is defined in a different scope and not available here
localFunc();

当你想创建公共方法可以使用的函数或方法,但又不希望外部调用者也能够调用或使用这些函数/方法时,私有方法是很有用的。

私有变量可用于存储公共方法或私有方法想要引用的状态,但您不希望外部调用者能够访问或能够干扰。