I’m working on a somewhat large-scale JS application and I want to break out some common functions into a utility class. I’m not quite clear on how I should go about it, however.
For example, say I have a bunch of shape-based classes that need to call a function in the utility class:
// Triangle class
Triangle.prototype = new Shape();
Triangle.prototype.constructor = Triangle;
function Triangle() {...}
Triangle.prototype.drawOutline = function() {
var outline = Utility.canvas.trace(this._canvas); // Trace the shape.
this._viewport.drawImage(outline, 0, 0); // Draw the traced outline.
}
// Circle class
Circle.prototype = new Shape();
Circle.prototype.constructor = Circle;
function Circle() {...}
Circle.prototype.drawOutline = function() {
var outline = Utility.canvas.trace(this._canvas); // Trace the shape.
this._viewport.drawImage(outline, 0, 0); // Draw the traced outline.
}
Does it make sense to instantiate the Utility class at the global level? I feel like there should be an additional level above it, something like Application so I’d have Application.Utility, Application.UI, and so on. Unfortunately, going this route forces each specialized shape class to know what the greater program structure is (so it can reference Application.Utility), which isn’t very good.
Is there a better, preferred manner to have specialized JS classes make use of generalized class functions that aren’t inherited?
Edit: It might help to say that I’m trying to relate this to an #include or import statement from C++ or Java. What’s the best way to go about this in JS?
Assuming that you’re wrapping all your code in an anonymous function then what I usually do is just create an object (namespace) and put all the utils there:
Then whenever you use it you just do
Utils.circle(...)that way you know when you’re using utils and it’s easy to keep track of them, add new ones, etc.In this case the simplest way is to create a
concat.shfile or similar and astart.jsandend.jsand add everything in between.start.js
utils.js
end.js
concat.sh
Order is important, of course.
If you’re into node.js check out grunt that does all of this for you with little configuration.
Otherwise, for more advanced stuff use CommonJS modules.