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

时间:2015-07-05 18:49:41

标签: javascript jquery

我只是看一下模块化模式的简单演示代码,看看:

// 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更多的是赋予函数的变量。

1 个答案:

答案 0 :(得分:2)

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();

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

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