I'm working on a project where we are doing a lot of custom javascript and especially jquery, on an mvc style project.
The only problem is that I keep adding more and more global functions/variables and they are piling up. I've got a few files but I'm unsure how to split some of the stuff up into separate files.
I've thought about composing some of these function and global variables into objects, but the object syntax in javascript seems a little awkward to me (because of the absence of classic classes). Though if I had a good example to follow maybe I could come around.
How do you deal with a project where the global javascript functions and variables start piling up like this?
In the editor, select a code fragment to convert into a function and press Ctrl+Alt+M or choose Refactor | Extract Method from the context menu. Alternatively, do one of the following: Press Ctrl+Alt+Shift+T and select Extract Method. From the main menu, select Refactor | Extract | Method.
Refactoring Makes Your Code Easier to Modify As you add new functionality, cohesion decreases. Abstractions aren't as clean anymore. By refactoring regularly, you update the code so that it reflects an improved understanding of the domain. This alignment enables easier modification.
A very simple way to pile a bunch of global variables and functions into a single global object:
// Awful pile of globally-scoped names
var foo = 1
var bar = 2
function go = function(){
console.log('Yeehaw!');
}
// Instead, just dump everything into a global-level object
var MyApp = {
foo: 1,
bar: 2,
go: function(){
console.log('Yeehaw!');
}
}
// Now access stuff like this
console.log(MyApp.foo);
console.log(MyApp.bar);
MyApp.go();
For "simple" top-level variables and functions, I can recommend this. There are plenty of improvements that can be made to this, but they'll probably fall under the category of premature optimizations; this is a great first step.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With