1

I came across below code written in node which I am trying to understand. There is a method process attached to prototype as well as to the object itself. Whats the difference? I understand the approach is used to have singleton instances for the object. However would like further explanation or reference to how this works.

var singleton;
var MyObj = function(opts) {//code}
MyObj.prototype = {
  process: function() {//code}  
}
MyObj.process = function process() {
  singleton.process();
}
MyObj.init = function init(opts) {
  singleton = new MyObj(opts);
}
module.exports = MyObj;
1
  • It looks like you're giving you the option of using it as a singleton or a constructor. Whichever works better for your situation. Commented Feb 1, 2016 at 17:05

1 Answer 1

1

I'll explain each block of code:

var singleton;

This variable is declared in the module but not exported. This means it is private to the module and exists within a closure.

var MyObj = function(opts) { /* code */ }

This is the constructor.

MyObj.prototype = {
  process: function() {//code}  
}

Every instance created using the MyObj constructor is given a process method.

MyObj.process = function process() {
  singleton.process();
}

This method exists on the prototype itself. When called, it executes the process method of the singleton object. Because the singleton object is private to this module, every call to MyObj.process executes the .process method of the same singleton object.

MyObj.init = function init(opts) {
  singleton = new MyObj(opts);
}

The init method is used to create an instance of the MyObj prototype. This instance is assigned to the singleton object. The singleton object is private to the module so every call to MyObj.init manipulates the same singleton instance, effectively overwriting the object that was previously stored in it. This ensures that the singleton object is always an instance of MyObj.

module.exports = MyObj;

The constructor is exported here. Note that the singleton object is not exported.

In summary

(new MyObj()).process() and MyObj.process() perform the same function because they use the same singleton instance. You can read about singletons in NodeJS here and here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.