Question: Where do you assign methods to an object? In Constructor or Prototype?
Adarsh Somani
Frontend engineer with experience in React, Angular and SSR (Holds canadian PR)
Before learning this, you need to understand about closure. Closure is a function which shares the lexical scope of outer function, hence it keeps hold on the memory even when outer function is resolved.
Now Consider the following case
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
this.getName = function() {
return this.name;
};
this.getMessage = function() {
return this.message;
};
}
So whenever call the constructor of MyObject, these functions get reassigned which is not memory efficient.
var obj = new MyObject('abc', 'Sample Message');
So it is better add methods to the prototype, unless you specifically need to create closures where both functions needs to share the same lexical environment.
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype = {
getName: function() {
return this.name;
},
getMessage: function() {
return this.message;
}
};
In following example, it is better to add inside constructor
function MyObject(name, message) {
_counter = 0;
this.message = message.toString();
this.getCounter = function() {
return this._counter;
};
this.setCounter = function(value) {
this._counter = value;
};
}
In above example, we are creating a private variable which is getting exposed to outer environment through getters and setters). Since both functions needs to share the same scope, we have added them inside constructor.