0

I have a big client-side javascript class defined for an application. I want to break this class into multiple files so people can work on the class separately and not interrupt each other. My class is called OC and I declared it like the following in a file called oc.js:

function OC(config) {
  // omitted for brevity
}

this class has many members and variables inside it. Now I'm willing to separate little bits of this file into two new files. So I created oc.connection.draw.js like the following:

OC.prototype = {
   _drawConnections: function (links) { omitted for brevity }       
}

first of all, It seems I don't have access to arguments of my main function (config) in the prototype. Is it any work around for that except creating a local variable for it? secondly is there any best practice for this in javascript community? My ideal result would be something like partial classes in .net framework.

Milad
  • 178
  • 1
  • 8
  • I don't know anything about .net so don't know what that means, but check out [RequireJS](http://requirejs.org/) – pstenstrm Jan 27 '14 at 07:09
  • Well, you can include your scripts in the browser and share a global namespace, or you can use some tooling on NodeJS, like Browserify, or something on the client like RequireJS. There are a few options, each with its own advantages and disadvantages. – elclanrs Jan 27 '14 at 07:14
  • 2
    _“I want to break this class into multiple files so people can work on the class separately and not interrupt each other”_ – instead of doing that, maybe you should look into version control systems and merge tools … – CBroe Jan 27 '14 at 07:27
  • @CBroe The file is pretty big and tracking all the changes and their affect on each other is pretty time consuming. Is there any good merge tool that you can recommend? – Milad Jan 27 '14 at 10:34
  • @elclanrs thanks I will check both browserify and requirejs :-) – Milad Jan 27 '14 at 10:35
  • @pstenstrm Thank you I will check requirejs out :-) – Milad Jan 27 '14 at 10:35

1 Answers1

0

Your constructor should be like this:

function OC(config) {
    this.config = config;
    // more stuff here
}

Then you can extend it like this:

OC.prototype._drawConnections = function(links) {
    // this.config is the config data
    // more code here
}

It'll work, just make sure to combine all your script files into one before shipping to production ;)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • is 'this.config = config' any different if I omit the this keyword? I know both work, but just wanna know the difference. – Milad Jan 27 '14 at 10:32
  • Variables defined with this are members of the instance you create with the constructor function. Variable declare as var could be available through closure only to code in the constructor function (not available on prototype declared functions. More on constructor functions and prototype herehttp://stackoverflow.com/a/16063711/1641941 – HMR Jan 27 '14 at 14:20