What are the benefits of using constructors in JavaScript?

I am working on a reorganization of a large and undocumented JavaScript library. One of the proposed refactoring is the implementation of constructors in code, rather than the dynamic construction of an object. Example below:

Instead:

var myLibObj = new Object();
myLibObj.SomeProperty =
{
   FooFunction: function(){/*Do Something Cool*/}
}

Proposed Change:

function myLibObjConstructor(){
  this.SomeProperty = {FooFunction: function(){/*Do Something Cool*/}}
  return this;
}

var myLibObj = new myLibObjConstructor();

Is there any advantage to changing the code?

+3
source share
3 answers

One of the benefits is that myLibObjConstructor can be reused somewhere else

+2
source

If existing code already works without the need for constructors, the benefits of switching to constructors may be minor or nonexistent.

However, the general advantages of using constructors are:

  • "", instanceof constructor, .
  • , . "private", .., .
  • , .
+1
0
source

All Articles