组织大型javascript文件

组织大型javascript文件

本文介绍了组织大型javascript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始为网站积累相当多的Javascript代码。到目前为止,所有内容都在一个文件中,并且该文件变得无法维护。如果一行中有错误,则整个文件都会中断。

I've started to accumulate quite a few lines of Javascript code for a website. Everything has been in one file so far and that file is becoming impossible to maintain. If there is an error in one line, the entire file breaks.

我尝试将代码拆分为多个文件,但是对象之间有一些共享方法,如: validateEmail(地址)

I've tried splitting the code up into multiple files but there are some shared methods across objects like: validateEmail(address).

现在,我将我的代码组织成对象,如下所示:

Right now, I have my code organized into objects, like so:

var ProductPage = {
    addToCartBtn: "#add-to-cart",

    init: function() {
        ProductPage.initAddToCartPopup();
        ProductPage.initSidebar();
        ...
    },
    ...
};

然后,我打电话给 ProductPage.init() on $(document).ready

Then, I call ProductPage.init() on $(document).ready.

我的问题是:拆分时 ProductPage 进入单独的文件 ContactPage ,例如我无法访问 ContactPage.validateEmail() 。我相信这是因为我的代码包含在jQuery中:

My issue is: when splitting ProductPage into a separate file as ContactPage, for example I cannot access ContactPage.validateEmail(). I believe this is because my code is wrapped in jQuery's:

(function ($) {
    ...
})(jQuery);

有没有人了解他们如何组织大型Javascript系统?此外,我计划进行优化,将所有这些放入一个文件并压缩它。因此,任何有利于可维护性和易于优化的方法都会非常棒。

Does anyone have insight on how they have organized large systems of Javascript? Also, I plan on doing optimization with putting all of this into one file and compressing it. So, any method which will benefit both maintainability and ease of optimization would be awesome.

推荐答案

validateEmail 在我看来,类似的方法是功能。功能我的意思是, y = f(x)。这些功能不会更改状态,而是返回输出,这些输出在传递的输入上计算

validateEmail like methods are functional in my opinion. By functional I mean, y = f(x). These functions are not changing the state but returning an output which are being computed on the passed input.

您可能希望将所有实用程序功能方法保留在单独的模块中,并将标记为全局命名空间。确保在使用之前加载此(这些)实用程序模块

You might want to keep all this utility functional methods in a separate module and tag it to a global namespace. Make sure to load this(these) utility module(s) before utilizing them.

您可以使用用于依赖关系管理

这篇关于组织大型javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:15