YMC
YMC

Reputation: 5462

Is it possible to split huge javascript file by few smaller files preserving its structure?

I have pretty big javascript class with bunch of methods stored in a single js file. This methods can be logically categorized like common methods, methods to filter data, navigation methods etc. Now I want this class being split by separate files each containing its own specific category methods and leaving all properties and common methods in the current file. Shortly speaking I need something that c# partial keyword is used for.

I would like to avoid using prototype as it means I have to type class name for every function like class.prototype.functionname = function () { ... } that does not look great.

UPDATE: This is how my class looks like

function MyClass() {
    var self = this;
    self.common = function() {...}
    self.filterData = function() {...}
    self.navigate = function() {...}
}

I do not know how to handle self properly with prototypes or extension

Upvotes: 0

Views: 1066

Answers (1)

Bergi
Bergi

Reputation: 664548

If your class does not use the prototype, you have little chance - it is one [too] big function. However, such big functions shouldn't exist anyway, are you sure you need it to be a class (with multiple instances)? Then you should move the functions to the prototype as far as you can. If not, a singleton would make more sense for you, which is essentially nothing more than an object literal. You also might have a look at the [revealing] module pattern, which is what you need (or one of its flavors) - the (sub) modules usually can be spread easily across different files, potentially using a dependency tracking loader.

If it does, you can easily split it up into the single parts. That does not mean you would need to repeat class.prototype.… = …, you can just use helper functions like extend

MyFavLibrary.extend(class.prototype, {
    functionname: function functionname() {…},
    …
});

or a simple IEFE-closure:

(function(proto) {
    // even some place for static, private helper functions
    proto.functionname = functionname() {…};
    …
})(class.prototype);

Upvotes: 2

Related Questions