我想知道我应该如何设计我的javascript文件。
我将有一个global.js
文件,用于所有项目。然后每个项目都有自己的project.js
文件,其中包含该项目的特定功能/覆盖/设置。
所以我想在 global.js 文件中编写所有“全局”函数:
Global = function() {
var config = {'alpha': 1};
function getConfig() {
return this.config;
}
function printConfig() {
console.log(this.getConfig());
}
};
Global.prototype.echoConfig = function() {
console.log(this.getConfig());
};
我想我的 project.js 文件看起来像是:
var project = new Global();
Global.prototype.projFunc = function() { return 2; };
但是,我还没想出如何从global.js
获取配置?
我正在使用jQuery,并注意到$ .extend函数看起来不错,但是我想首先为我的global.js和project.js设置结构 - 一般来说我可能想要将大多数函数从project.js移动到global.js,但是可能有一个或两个项目只需要该应用程序的一个特定函数。
答案 0 :(得分:2)
您需要在公共范围内使用getConfig
,并且由于您以“私人”方式声明config
,因此您无法使用this.config
来获取config
,只需使用config
。
Global = function() {
var config = {'alpha': 1};
this.getConfig = function() {
return config;
}
function printConfig() {
console.log(this.getConfig());
}
};