Seeker
Seeker

Reputation: 2475

Splitting a Javascript file

I have a 8000 line JS file, which I want to divide. My JS contains a single class with many methods under it. like

   var myClass:{
       method1:function(param1){
        //Useful code
       },
      method2:function(param1){
        //Useful code
       },
      method3:function(param1){
        //Useful code
       },
       method4:function(param1){
        //Useful code
       },
 ........
}

Now I want to divide this file that means am going to divide the class itself. Can I define few function in one file and rest in another file inside the same class. Some thing like the bellow mentioned code

File1.js:  var myClass:{
               method1:function(param1){
                //Useful code
               },
              method2:function(param1){
               //Useful code
              }
..........
          }

File2.js: 
     var myClass:{
               method3:function(param1){
                //Useful code
               },
              method4:function(param1){
               //Useful code
              }
..........
          }

Is there any way I can achieve this and How ?

Upvotes: 2

Views: 141

Answers (2)

neelsg
neelsg

Reputation: 4842

The solution suggested by @vanthome should work. To make it a bit more structured and perhaps make the order of the files more obvious and matter a little less, you could do it like this:

FileHeader.js

var myClass = {};

File1.js

myClass.method1 = function(par1) {
    // Useful code
};
myClass.method2 = function(par1) {
    // Useful code
};

File2.js

myClass.method3 = function(par1) {
    // Useful code
};
myClass.method4 = function(par1) {
    // Useful code
};

Upvotes: 1

vanthome
vanthome

Reputation: 4924

sure, you can define the class in File1.js like so:

var myClass = {
           method1:function(param1){
            //Useful code
           },
          method2:function(param1){
           //Useful code
          }
          ..........
      };

and then because functions are objects in JS, just extend it in File2.js like this:

 myClass.method3 = function(param1){
            //Useful code
           };
 myClass.method4 = function(param1){
           //Useful code
          };
          ..........

You just have to maintain the order when including the files in the browser or wherever you use them.

Upvotes: 2

Related Questions