【问题标题】:JavaScript organization | Module pattern w/ modulesJavaScript 组织 |带模块的模块模式
【发布时间】:2012-04-25 04:34:34
【问题描述】:

我将我的代码组织成 20-60 行的模块,通常采用模块模式。我想要一个结构良好的面向对象的 JavaScript 库。

这是最好的方法吗?该代码已经过测试并且可以运行。

我喜欢它,因为程序员可以从库中提取模块并根据需要使用它们,它们是自包含的。

这里是工具、消息、效果和文本,都包含在 NS 中。

问题?

这是组织我的图书馆的好方法(最佳做法)吗?

注意

到目前为止,cmets 和答案中的共识为 0...非常令人沮丧。

外部模块模式

var NS = ( function ( window, undefined ) 
{ 
/* All Modules below here */ 
} )( window );

工具

/**
 *Tools
 *    getTimeLapse - benchmark for adding
 */

var Tool = ( function () 
{
    var Tool = function ( ) 
    {
    };
    Tool.prototype.getTimeLapse = function( numberOfAdds ) 
    {
        var end_time;
        var start_time = new Date().getTime();
        var index = 0;           
        while ( index <= numberOfAdds )
        {
            index++;
        }
        end_time = new Date().getTime();
        return ( end_time - start_time );
    };
    return Tool;
} () );

留言

/**
 *Message
 *    element - holds the element to send the message to via .innerHTML
 *    type - determines the message to send
 */

var Message = ( function () 
{
    var messages = 
    {
        name:         'Please enter a valid name',
        email:        'Please enter a valid email',
        email_s:      'Please enter a valid email.',
        pass:         'Please enter passoword, 6-40 characters',
        url:          'Please enter a valid url',
        title:        'Please enter a valid title',
        tweet:        'Please enter a valid tweet',
        empty:        'Please complete all fields',
        same:         'Please make emails equal',
        taken:        'Sorry, that email is taken',
        validate:     'Please contact <a class="d" href="mailto:foo@foo.com">support</a> to reset your password',
    };
    var Message = function (element) 
    {
        this.element = element;
    };
    Message.prototype.display = function( type ) 
    {
        this.element.innerHTML = messages[ type ];
    };
    return Message;
} () );

效果

/**
 *Effects
 *    element - holds the element to fade
 *    direction - determines which way to fade the element
 *    max_time - length of the fade
 */

var Effects = ( function () 
{
    var Effects = function ( element )
    {
        this.element = element;
    };
    Effects.prototype.fade = function( direction, max_time ) 
    {
        var element = this.element;
        element.elapsed = 0;
        clearTimeout( element.timeout_id );
        function next()
        {
            element.elapsed += 10;
            if ( direction === 'up' )
            {
                element.style.opacity = element.elapsed / max_time;
            }
            else if ( direction === 'down' )
            {
                element.style.opacity = ( max_time - element.elapsed ) / max_time;
            }
            if ( element.elapsed <= max_time ) 
            {
                element.timeout_id = setTimeout( next, 10 );
            }
        }
        next();
    };
    return Effects;
} () );

文字

/**
 *Text
 *    form_elment - holds text to check
 */

var Text = ( function () 
{
    var Text = function ( form_element )
    {
        this.text_array = form_element.elements;
    };
    Text.prototype.patterns = 
    {
        prefix_url:     /^(http:)|(https:)\/\//,
        aml:            /<(.+)_([a-z]){1}>$/,
        url:            /^.{1,2048}$/,
        tweet:          /^.{1,40}$/, 
        title:          /^.{1,32}$/,
        name:           /^.{1,64}$/, 
        email:          /^.{1,64}@.{1,255}$/,
        pass:           /^.{6,20}$/
    };
    Text.prototype.checkPattern = function( type ) 
    {
        return this.patterns[ type ].exec( this.text_array[type].value );
    };
    Text.prototype.checkUrl = function( type ) 
    {
        return this.patterns[ type ].exec( this.text_array.url.value );
    };
    Text.prototype.checkSameEmail = function() 
    {
        return ( ( this.text_array.email.value ) === ( this.text_array.email1.value ) );
    };
    Text.prototype.checkEmpty = function() 
    {
        for ( var index = 0; index < this.text_array.length; ++index ) 
        {
            if ( this.text_array[ index ].value === '') 
            { 
                return 0; 
            }
        }
        return 1;
    };
    return Text;
} () );

【问题讨论】:

  • 它远非最好,因为您使用全局变量
  • 所有这些文件都在全局范围内吗? var Text = ...
  • @Raynos 我不想告诉你,但不可能没有至少一个全局 :)
  • @Raynos 即使您使用 AMD 或 commonJS 等模块加载系统,这些库仍然会暴露全局变量。没有访问方式就无法执行 javascript。
  • @Raynos 以 require.js 为例,require 和 define 都是全局变量。我很难理解你怎么不理解这个概念。

标签: javascript


【解决方案1】:

我建议更改以使您的代码更简洁并减少其占用空间的一件事是立即设置原型属性,而不是这样做

Object.prototype.method1 = function(){};
Object.prototype.method2 = function(){};

你会的

Object.prototype = {
    method1: function(){},
    method2: function(){}
};

如果您需要保留构造函数引用,这是推荐的,您应该在之后重新分配构造函数。 See this answer for more details.

【讨论】:

  • 1) 从不重新分配Object.prototype。 2) 永远不要在没有放回constructor 属性的情况下重新分配原型
  • @Raynos 你能解释一下吗?
  • @DanielRibeiro 1) 是显而易见的,2) stackoverflow.com/questions/4944278/…
  • @The All Foo 我不这么认为。
【解决方案2】:

我个人更喜欢使用像ncore这样的模块化代码组织库

这鼓励您将代码编写为一组模块(每个文件一个模块),然后使用依赖注入和引导将它们挂钩。

代码有点可移植,因为模块本身就是对象,但是如果不使用 ncore,就会失去优势。

leaderboard app 显示了 OO 代码组织的详细示例

【讨论】:

    【解决方案3】:

    一些建议...首先是创建一个命名空间对象作为库的范围... jQuery 使用“jQuery”和“$”,下划线使用“_”。我倾向于使用“CompanyName.SiteName”

    if (typeof CompanyName == "undefined") var CompanyName = {};
    CompanyName.SiteName = CompanyName.SiteName || {};

    第一行明确检查未定义,因为您会在许多浏览器中遇到错误,否则使用 SiteName 属性上的方法查找根变量。

    从那里,我会做一些调整...当您在内联调用匿名函数时,最好将整个调用包装在括号内。

    CompanyName.SiteName.ModuleName = (function(w){
        ...
        return moduleImplementation;
    }(window || this)); //CompanyName.SiteName.ModuleName

    这往往会通过让括号包裹整个内容并在模块声明的末尾添加注释来避免混淆。

    根据上面的评论,您可能希望将原型声明作为更单一的声明。我建议不要这样做,因为更长的模块会使可读性成为问题。

    myModule.prototype = {
        "method1": function(){
        }
        ...
        "methodN": function(){
           //by the time you get here, you may not see the top, and where you are nested in
        }
    };
    
    //with the dot-notation, or hash notation
    myModule.prototype.methodN = ...
    myModule.prototype["methodN"] = ...
    //you can see where you are binding to at that function
    

    您可能还想查看RequireJS 和AMD

    还有处理更简单对象和使用函数绑定器的概念。将您的库视为一组函数(类似于 C 导出),它们被传递并使用更简单的对象/类型。这实际上取决于您的需求/使用情况以及您的需求和使用的具体情况。

    您可能还想查看一些示例,例如 KnockoutJS、Underscore 和 Backbone 等 JavaScript 库。

    【讨论】:

    • 命名空间不好。不要使用它们
    • @Raynos 命名空间很好。它们有利于代码隔离。糟糕的是,当您进行多个深度嵌套的命名空间调用时……通常最好为您的命名空间/函数创建一个局部变量别名。但这是模块开发的一个单独问题。除非你有促进封装的环境(比如节点)。
    • @TheAllFoo 我看不到 Arc 作为命名空间,我看到的是 Arc、工具和消息。
    猜你喜欢
    • 2011-05-05
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多