Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: when to define functions inside constructor and when to use prototype?

I'm learning Javascript and have several questions concerning Javascript and OOP. I've noticed different declarations of functions in "classes" in various tutorials. First is the inside constructor:

Class = function () {
  this.doSomething = function() {....};
}

And the other one is:

Class = function () {}
Class.prototype.doSomething  = function() {....};

In which situations should the first construction be used, and in which situation should the second construction be used?

And the other question is: have I understood correctly that there's no protected properties or methods in js? What is to be used instead?

Thank you in advance!

like image 920
Eugeny89 Avatar asked Nov 13 '12 10:11

Eugeny89


1 Answers

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 :

  • the enclosing of specific values
  • other types of specific functions (you might build a different function each time)

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() {
like image 191
Denys Séguret Avatar answered Oct 21 '22 18:10

Denys Séguret