Creating reusable code is one of the primary objectives we developers have so we can write less and more maintainable code later. However, with JavaScript most of us developers haven’t really worked on writing better code for a long time.
With the prevalence of Node.js and newer JavaScript libraries we need to upgrade our coding skills and write more reusable code. With OOP we do this writing classes we can create objects from. We can do something very similar in JavaScript.
If you go diving through JavaScript frameworks you will see the word prototype used quite a bit on base objects. What it does is adds a function to an object for you to call later from each instance of the object. If you use a prototype then you can call functions again from each instance independently.
To create a new object you need to define it first.
Defining Your Class
World = function(){
this.spinning = false;
}
We created a World function and set an instance variable of spinning to false.
Adding Functions
Add the following below your function declaration not inside.
World.prototype.spinCore = function() {
console.log("spinning core");
this.spinning = true;
}
World.prototype.addToSurface = function(thing) {
if(this.spinning) {
console.log("Added '" + thing + "' to worlds surface");
} else {
console.log("Sorry your planet core is not spinning");
}
}
As you can probably tell we have created a couple of functions for our world class. The idea is in order to add stuff to the surface of the planet the core needs to be spinning.
Lets Use It
In order to use our class we need to instantiate a new object and start using it.
w = new World();
w.spinCore();
>>> spinning core
w.addToSurface('person');
>>> added 'person' to words surface
n = new World();
n.addToSurface('animals');
>>> Sorry your planet core is not spinning
Conclusion
So that is a basic way to create re-usable code so you can have objects. There is much more you can do to write better code this is just a small part of it, and a good starting point. Hopefully you can start writing better code too. I have gotten better as I have been researching ways to write better JavaScript.

