我应该封装我的JavaScript库吗?

问题描述:

我有大约600行javascript执行ajax调用,dom操作,测试处理等等。

I have about 600 lines of javascript that performs ajax calls, dom manipulation, test processing, and other things.

我想让它成为其他人可以使用的库使用。

I want to make it a library that others can use.

执行此操作的步骤是什么?

What are the steps to doing this?

我的第一个想法是将整个库封装在模块模式中。之前有人建议这样做有助于解决www.jshint.com问题。

My first thought was to encapsulate the entire library in the module pattern. Someone suggested this earlier to help with a www.jshint.com issue.

但我认为这可能是一个好主意。

But I thought it might be a good idea in general.

我应该封装整个库吗?


  • 我应该使用模块模式吗?

信息隐藏是一种古老而众所周知的方法,可以使代码更安全,更模块化。它是许多令人敬畏的事情背后的基本原则之一,如抽象数据类型面向对象的编程

Information Hiding is an old and well known way to make code safer and more modularized. Its one of the basic principles behind many awesome things like Abstract Data Types and Object Oriented Programming

(是的,局部变量和模块模式是在Javascript中隐藏代码的唯一方法)

(And yes, local variables and the module pattern are the only way to hide code in Javascript)

var MyModule = (function(){
    //variables in the wrapper function are local and
    // can't be seen elsewhere

    var my_var;

    function my_private_implementation_function(){ ... }

    function my_api_function(){
    }

    //return public functions
    return {
       my_api_function: my_api_function
    };
}()); //immediatelly run the module code
      //and set MyModule to the return value

//Now we can use things exported from the module

MyModule.my_api_function();

//but we can't access the prvate stuff

MyModule.my_var; //can't do this