了解 JS 模块模式的工作原理

发布于 2024-10-05 21:33:39 字数 3610 浏览 6 评论 0原文

我试图理解与 jQuery 一起使用的 js 模块模式。我已经对此进行了几次编辑,并将尝试最终对我的技能水平进行良好的练习(几个月前刚刚接触 jquery)。

这篇文章中没有直接的问题。我更希望获得关于如何在大型网站中正确使用模块模式(与 jquery 一起)的反馈和输入。

更新:我添加了一堆示例,以便了解所有编写方式的概述,并尝试涵盖任何陷阱。

/* 
Not all browsers works with console.log, so we want to make sure that
console.log is defined. This defines the consol.log and send the messages
into an alert.
*/
if(!window.console) console = {
  log: function(s) { 
    alert(s); // alert since we dont have the firebug console
  }
};

// Check if namespace is defined
if (typeof (CompanyName) === 'undefined') {
    CompanyName = {};
}

// Or if AppName under CompanyName...

if (typeof (CompanyName.AppName) === 'undefined') {
    CompanyName.AppName = {};
}

// Our namespace
CompanyName.AppName = (function ($) {

    // CHAINING
    var _first = function () {
        // Important to always start with "var"
    },

    _second = function () {
        // Chained (  ...},  ) so it doesnt need "var"
    },

    _third = "Just a var", // Variables just ends with ,

    _four = "Another var"; // Closing the chain with ;

    var _anotherFirst = function () {
        // Previous chain of var's was ended with ; so this var needed "var" in order to start.
    };

    g_globalVar = "I'm free!"; // When starting a var without "var", it becomes global.

    g_globalMethod = function () { 
        alert("I'm free too!"); // Global method.
    };

    g_chainedGlobalVarOne = "We are free!",
    g_chainedGlobalVarTwo = "We are free!";

    // Private Variables
    var _privateVar = "privateVar: accessed from within AppLaunch.Admin namespace";

    // Private Methods
    var _privateMethod = function () {
       log("privateMethod: accessed only from within AppLaunch.Admin");
    }; // Last variable in a chain must always end with ; before the return {}

    function log() {
        if (window.console && window.console.log)
            window.console.log('[AppName] ' + Array.prototype.join.call(arguments, ' '));
    };

    return {
        init: function () {

            // Calling private
            _privateMethod();

            // Calling Public
            this.myPublicMethod();

            // Also Calling Public
            CompanyName.AppName.myPublicMethod();

            // Calling Other namespace's Public Method (when exists)
            CompanyName.OtherNamespace.externalPublicMethod(); 
        },

        // Public
        myPublicMethod: function() {
            log("myPublicMethod");
        },
        // In a View (MVC), I could have a page called myPage where I want to init
        // some particular functions. myPage can be called just like init. 
        myPage: function() { 
            _second();
            _third();
        }

    }
})(jQuery); 

// Initialize
jQuery().ready(function() {
    CompanyName.AppName.init()
    CompanyName.AppName.myPublicMethod();
});  

尝试了解正在发生的事情(请随意提供更正或更好的解释):

Company.AppName = (function ($) { ...

这里创建了命名空间 Company.AppName。我在里面设置了 ($),这样我就可以使用 $,而不会与任何其他可能使用 $ 的库发生冲突。

})(jQuery); 

据我所知,这里的方法和变量都是返回到命名空间的...})();通过在 () 中添加 jQuery,它会告诉它 $ 表示 jQuery。

初始化

我不确定这里的最佳实践是什么,但我会添加到目前为止我所知道的。

在 js 文件中初始化:

jQuery(function() { 
    AppLaunch.Admin.init();
});

从文件初始化:

<script type="text/javascript">
// Shorthand for jQuery(document).ready(function() { ... }

jQuery(function($) { 
    AppLaunch.Admin.init($('#someSelector'));     
});
</script>

I'm trying to understand js module patterns in use with jQuery. I've edited this a couple of times and will try to end up with a good practice for my skill level (a couple of months fresh on jquery).

There's no direct question in this post. I'm more aiming for feedback and inputs on how to properly use the module pattern (together with jquery) in a large scale website.

Update: I've added a bunch of examples in order to get an overview of all ways of writing things, and try to cover any pitfalls..

/* 
Not all browsers works with console.log, so we want to make sure that
console.log is defined. This defines the consol.log and send the messages
into an alert.
*/
if(!window.console) console = {
  log: function(s) { 
    alert(s); // alert since we dont have the firebug console
  }
};

// Check if namespace is defined
if (typeof (CompanyName) === 'undefined') {
    CompanyName = {};
}

// Or if AppName under CompanyName...

if (typeof (CompanyName.AppName) === 'undefined') {
    CompanyName.AppName = {};
}

// Our namespace
CompanyName.AppName = (function ($) {

    // CHAINING
    var _first = function () {
        // Important to always start with "var"
    },

    _second = function () {
        // Chained (  ...},  ) so it doesnt need "var"
    },

    _third = "Just a var", // Variables just ends with ,

    _four = "Another var"; // Closing the chain with ;

    var _anotherFirst = function () {
        // Previous chain of var's was ended with ; so this var needed "var" in order to start.
    };

    g_globalVar = "I'm free!"; // When starting a var without "var", it becomes global.

    g_globalMethod = function () { 
        alert("I'm free too!"); // Global method.
    };

    g_chainedGlobalVarOne = "We are free!",
    g_chainedGlobalVarTwo = "We are free!";

    // Private Variables
    var _privateVar = "privateVar: accessed from within AppLaunch.Admin namespace";

    // Private Methods
    var _privateMethod = function () {
       log("privateMethod: accessed only from within AppLaunch.Admin");
    }; // Last variable in a chain must always end with ; before the return {}

    function log() {
        if (window.console && window.console.log)
            window.console.log('[AppName] ' + Array.prototype.join.call(arguments, ' '));
    };

    return {
        init: function () {

            // Calling private
            _privateMethod();

            // Calling Public
            this.myPublicMethod();

            // Also Calling Public
            CompanyName.AppName.myPublicMethod();

            // Calling Other namespace's Public Method (when exists)
            CompanyName.OtherNamespace.externalPublicMethod(); 
        },

        // Public
        myPublicMethod: function() {
            log("myPublicMethod");
        },
        // In a View (MVC), I could have a page called myPage where I want to init
        // some particular functions. myPage can be called just like init. 
        myPage: function() { 
            _second();
            _third();
        }

    }
})(jQuery); 

// Initialize
jQuery().ready(function() {
    CompanyName.AppName.init()
    CompanyName.AppName.myPublicMethod();
});  

Trying to understand what's happening (Feel free to provide corrections or better explanations):

Company.AppName = (function ($) { ...

Here the namespace Company.AppName is created. I set ($) inside so I can use the $ without it conflicting with any other libraries that might use $.

})(jQuery); 

As far as I know, the methods and variables are returned to the namespace here ...})(); and by adding jQuery inside () it'll tell it that the $ means jQuery.

Initializing

I'm not sure what's best practice here, but I'll add what I know so far.

Initializing within js file:

jQuery(function() { 
    AppLaunch.Admin.init();
});

Initializing from a file:

<script type="text/javascript">
// Shorthand for jQuery(document).ready(function() { ... }

jQuery(function($) { 
    AppLaunch.Admin.init($('#someSelector'));     
});
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落日海湾 2024-10-12 21:33:39

有很多地方会给你深入解释模块模式; jQuery 对它的使用非常标准。

这只是众多模块模式解释之一。

There are many places that will give you an in depth explanation of the module pattern; jQuery's usage of it is pretty standard.

This is just one of the many module pattern explanations out there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文