在我的项目中,我有很多.js
个文件,我使用Class
将每个js文件设为prototype.js
。例如,我有以下js文件。
每个文件都依赖于其他js文件。所以,js文件的可能结构是这样的:
four.js
var Four = Class.create();
Four.prototype = {
initialize : function(){
},
one: new One(),
two: new Two(),
three: new Three(),
firstMethod: function(){
var one = this.one; //Initializing
var two = this.two;
var three = this.three;
//do operations using the above class variables
},
secondMethod : function(){
var one = this.one; //again Initializing
var two = this.two;
//do operations using the above class variables
}
}
three.js所
var Three = Class.create();
Four.prototype = {
initialize : function(){
},
one: new One(),
two: new Two(),
four: new Four(),
firstMethod: function(){
var one = this.one; //Initializing
var two = this.two;
var four = this.four;
//do operations using the above class variables
},
secondMethod : function(){
var one = this.one; //again Initializing
var two = this.two;
//do operations using the above class variables
}
}
正如您在上面的代码示例中所看到的,我正在类One
的不同方法中初始化类Four
两次。这看起来真的很糟糕,因为对于每个方法我都在初始化已经初始化的同一个类。
编辑:我还在js文件One
和Two
中多次初始化three.js
和four.js
个类。以上说明仅是例如。实际上,在我的项目中,有超过20个js文件。
在我的项目中,我在所有js文件中遵循相同的结构。
我应该如何使这种结构有效?
PS:改变较少的解决方案非常有用,因为这是一个庞大且正在运行的项目,我现在不想承担风险。
答案 0 :(得分:1)
如果您需要在每种方法中使用单独的版本:
var Four = Class.create();
Four.prototype = {
initialize : function(One, Two){
// store for later use
this.One = One;
this.Two = Two;
},
firstMethod: function(){
var one = new this.One(); // Initializing
var two = new this.Two();
//do operations using the above class variables
},
secondMethod : function(){
var one = new this.One(); // again Initializing
var two = new this.Two();
//do operations using the above class variables
}
};
// 'inject' needed class constructor functions
var four = new Four(One, Two);
如果你需要整个Four对象的单一版本:
var Four = Class.create();
Four.prototype = {
initialize : function(One, Two){
// initialize and use later this.Xxx
this.One = new One();
this.Two = new Two();
},
firstMethod: function(){
//do operations using the above class variables
},
secondMethod : function(){
//do operations using the above class variables
}
};
// 'inject' needed class constructor functions
var four = new Four(One, Two);
修改强>
var Four = Class.create();
Four.prototype = {
initialize : function(one, two){
// initialize and use later this.xxx
this.one = one;
this.two = two;
},
firstMethod: function(){
//do operations using the above class variables
},
secondMethod : function(){
//do operations using the above class variables
}
};
// 'inject' needed objects
var four = new Four(new One(), new Two());