Reputation: 3731
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?
Upvotes: 9
Views: 14066
Reputation: 382132
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 :
All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.
Regarding your additional question : the following code builds a non directly accessible function :
Class = function () {
var imprivate = function(){...};
this.doSomething = function() { uses imprivate};
}
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 _
:
// private method
XBasedGrapher.prototype._ensureInit = function() {
Upvotes: 14