I’ve noticed different ways to add functions to "classes" in various tutorials. The first is inside the class’ constructor:
Class = function () {
this.doSomething = function() {...};
}
The other one is:
Class = function () {}
Class.prototype.doSomething = function() {...};
In which situations should one be used over the other?
Is my understanding that there are no protected properties or methods in Javascript correct? If so, what should be used instead?
When you define a function inside the constructor as
this.myFunction=..., it is specific to your instance. This means that it must be constructed and kept in memory for all instances, which may be heavy. It also can’t be inherited .The only valid reason to do this are :
Most often, what you really need is a function defined on the prototype.
From the MDN on objects :
Regarding your additional question : the following code builds a non directly accessible function :
A downside is that you have a different function instance for each instance of
Class. This is most often done for modules (from which you have only one instance). Personally, I prefer to do exactly as suggested by ThiefMaster in comment : I prefix my private functions with_: