H5、CSS、JS

Namspacing-自用工具库

2016-05-14  本文已影响8人  前端历险记

自用工具库,主要用来收集一些常用的js工具,参考有几种方法:

 var Deep = ( function() {
    // Private variable
    var priate_var;

    // Private method 
    function private_method() {
        // do something
    }

    // Return public method
    return {
        method_1 : function() {
            // do something
        },

        method_2 : function() {
            // do something
        } 
    }
 })();

改良版.统一输出,后期工具库庞大起来,能快速检查是否重复:

 var Deep = ( function() {
    // Private variable
    var priate_var;

    // Private method 
    function private_method() {
        // do something
    };

    function method_1() {

    };

    function method_2() {

    };

    // Return public method
    return {
        method_1 : method_1,
        method_2 : method_2
    }
 })();

参考链接
Namespacing your JavaScript

Douglas Way:

// Constructor Function
function DeepContainer(ele){
    // Private variable
    this.member = ele;
    var priate_var = 3;
    var that = this;

    // Private method
    function private_method() {

    }

}

// Inherit method
DeepContainer.prototype.method_1 = function() {
    // do something
};

DeepContainer.prototype.method_2 = function() {
    // do something
};

var Deep = new DeepContainer();

参考链接:
Private Members in JavaScript

Stackoverflow一个回复参考,体系完整,包含了注释的格式:

/**
  * Namespace <i> Example </i> created to group other namespaces of the "Example".  
  */
Exc = {};
/**
  * Namespace <i> ui </i> created with the aim of grouping namespaces user interface.
  */
Exc.ui = {};

/**
  * Class <i> maskdInput </i> used to add an input HTML formatting capabilities and validation of data and information.
  * @ Param {String} mask - mask validation of input data.
  */
Exc.ui.maskedInput = function (mask) {
    this.mask = mask;
    ...
};

/**
  * Class <i> domTips </i> used to add an HTML element the ability to present tips and information about its function or rule input etc..
  * @ Param {String} id - id of the HTML element.
  * @ Param {String} tips - tips on the element that will appear when the mouse is over the element whose identifier is id <i> </i>.
  */
Exc.ui.domTips = function (dom, tips) {
    this.dom = gift;
    this.tips = tips;
    this.internal = {
        widthEstimates: function (tips) {
            ...
        }
        formatTips: function () {
            ...
        }
    };
    ...
};

参考链接
Commonly accepted best practices around code organization in JavaScript

Douglas Way扩展有无限可能,适合在做组件中面向对象拆分功能块,或者做dom兼容直接更改原型链。如果从单一工具库,可选用最后一种形式搭出框架(ui,dom,utils...),单一内容如工具库(utils)使用第一种改进版最好。

p.s结合模块开发,必然会有更优良的方法,此题内容较早,有一处早期关于模块化的探讨,扩展阅读
JavaScript Module Pattern: In-Depth

上一篇下一篇

猜你喜欢

热点阅读