2012-09-02 20 views
0

我的应用程序使用这个主要的对象,因为你看到大部分的工作是在这个方法中完成的。问题是如果我想将它全部写入一个文件,则此对象将变得太大。代码将很难调试。有什么方法可以用来将这个对象分割成多个文件(就像一个文件中的每个函数一样)? 我也希望能够访问和更改这些函数中的displayArray,userOptions和查询变量。
各种建议表示赞赏。谢谢:)如何将我的javaScript代码打碎成多个文件?

application = { 
    displayArray : new Array(), 
    userOptions : new Array(), 
    query : '', 
    status : false, 

    initilize : function() { 
     //its going to initialize displayArray, userOptions and status. 
    }, 

    loadOptions : function() { 
     //this function builds userOptions array 
    }, 

    JSONConverter : function() { 
     //this function uses query to builds displayArray 
    }, 

    display : function() { 
     //this function will use displayArray to build HTML elements on page 
    }, 

}; 

回答

0

你可以!写几个剧本名为.js,然后将它们嵌入在像这样的HTML文件:

<head> 
    <script type="text/javascript" src="script1.js"></script> 
    <script type="text/javascript" src="script2.js"></script> 
</head> 

This是如何做到这一点的好例子。 (source

1

例如:

// file: application.js 
(function (window, undefined) { 
    var application = { 
    // ... 
    }; 
    window['application'] = application; 
}(window)); 

// file: application-module1.js 
(function (application, window, undefined) { 
    var module_foo = { 
    // ... 
    }; 
    application['module_foo'] = module_foo; 
}(application, window)); 

// file: application-module2.js 
(function (application, window, undefined) { 
    var module_bar = { 
    // ... 
    }; 
    application['module_bar'] = module_bar; 
}(application, window)); 
0

abstract.js

function abstractClass(construct_options){{ 

} 

someObject.js

someObject.prototype = new abstractClass(); 
someObject.prototype.foo = function(){ 


} 

otherObject.js

otherObject.prototype = new abstractClass(); 
otherObject.prototype.toe = function(){ 


} 

进一步,你可以这样做:

var a = new someObject(); 
var b = new otherObject(); 
+0

我喜欢抽象类的想法谢谢。 –

0

您可以将所有功能集成到单独的文件,并将它们添加到您的应用程序的PROTOTYP。

文件initialize.js:

function initialize() { 
    this.displayArray = new Array(); 
} 

文件initilize.js:

function() Application{ 
    this.userOptions = new Array(); 
    this.query = ''; 
    this.status = false; 
    this.initialize(); 
} 

Application.prototype.initialize = initialize; 

该解决方案将polute全局名字空间与外部文件中的所有功能。所以,如果它的一个大项目,你应该开始使用和AMD的解决方案就像requirejs

文件initialize.js:

define(function() { 
    return function() { 
     this.displayArray = new Array(); 
    } 
}) 

文件initilize.js:

define(['initialize'], function (initialize) { 
    function() Application{ 
     this.userOptions = new Array(); 
     this.query = ''; 
     this.status = false; 
     this.initialize(); 
    } 

    Application.prototype.initialize = initialize; 
    return Application; 
}) 
+0

非常感谢,你帮了我很多,我喜欢使用nameSpaces的想法。 –

0

你可以在一个文件中定义应用程序的“类”,然后使用原型将每个函数添加到单独的文件中,例如

var application = function() { }; 

application.prototype.method1 = function (arg1) { 
window.alert(arg1); 
} 

var a = new application(); 
a.method1('Hello, World!'); 
相关问题