OOP suggests only exposing variables and methods that you want the user to be able to access. I have been using the public method declaration (i.e. prototype) for my object.
DrawShape = function() {
}
DrawShape.prototype.circle = function() {
// draw logic here
}
DrawShape.prototype.square = function() {
// draw logic here
}
This method seems to be the most efficient as the method isn't rewritten every time an instance in instantiated. However I have found that to create good DRY, modular code I have had to create methods that are only intended to be accessed by other methods (i.e. private methods).
DrawShape = function() {
}
DrawShape.prototype.circle = function() {
var colour = this.setColour();
// draw logic here
}
DrawShape.prototype.square = function() {
var colour = this.setColour();
// draw logic here
}
DrawShape.prototype.setColour = function() {
return "blue";
}
Here I have created the method called setColour that is only intended to be run by the other methods. The problem is that the method is public and could be called by anyone or anything.
I could move the method into the object constructor... But this means that I am no longer saving memory (i.e. it will be rewritten every time an instance is instantiated) and it also means that I would have have to move all my other methods into the constructor.
What is the best practices in JavaScript when it comes to creating objects?