I have a javascript object, which I've added a number of prototyped functions to, which mostly depend in some way on the members of the object.
myForm() {
this.property1 = "Prop1";
this.property2 = "Prop2";
}
myForm.prototype.loadValues = function(){ /*...*/);
myForm.prototype.setValues = function(){ /*...*/);
myForm.prototype.doStuff = function(){ /*...*/);
There are enough functions/code that it is currently sitting at ~4 thousand lines, and it is driving me nuts every time I have to debug it using dev tools/firebug. I was thinking of splitting this up as such.
myForm.js -
myForm(){
this.property1 = "Prop1";
this.property2 = "Prop2";
new myFormLoadActions();
new myFormSetActions();
new myFormDoStuffActions();
}
myFormLoadActions.js
myFormLoadActions(){
myForm.prototype.loadValues = function(){ /*...*/);
}
myFormSetActions.js
myFormSetActions(){
myForm.prototype.setValues = function(){ /*...*/);
}
myFormDoStuffActions.js
myFormDoStuffActions(){
myForm.prototype.doStuff = function(){ /*...*/);
}
I've trialled this, and it seems to work functionally. Is this a reccomended way of dealing with a large number of prototyped functions, or is there a better way?
Keep your old code, but simply scatter assignments to prototype over multiple files:
File 0
myForm() {
this.property1 = "Prop1";
this.property2 = "Prop2";
}
File 1
myForm.prototype.loadValues = function(){ /*...*/);
File 2
myForm.prototype.setValues = function(){ /*...*/);
As I noted in the comments, this is just a problem of one class doing too much but you realize that and just want smaller files, so here you go :)
To me, that looks a bit strange. I mean, you're constructing objects for their 'side-effects' (adding properties to a different object's prototype), and then throwing them away immediately:
myForm(){
...
new myFormLoadActions();
...
}
The object that you've "newed up" doesn't actually do anything after instantiation, and you're not holding a reference to its instance, so it would be better just to be a callable function:
myForm(){
...
myFormLoadActions(this);
...
}
That's just my humble opinion though, feel free to argue!
I would recommend this approach coz it seems more neat to me and also not difficult to debug.
myForm() {
this.property1 = "Prop1";
this.property2 = "Prop2";
}
myForm.prototype = {
loadValues: function(){ /*...*/),
setValues: function(){ /*...*/),
doStuff: function(){ /*...*/),
.
.
.
}
Another approach:
myForm(){
this.property1 = "Prop1";
this.property2 = "Prop2";
addFunctionsToPrototype();
}
addFunctionsToPrototype(){
myForm.prototype.loadValues = function(){ /*...*/);
myForm.prototype.setValues = function(){ /*...*/);
myForm.prototype.doStuff = function(){ /*...*/);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.