Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What advantages are gained by using constructors in JavaScript?

Tags:

javascript

I'm working to refactor a large and undocumented JavaScript Library. One of the proposed refactorings is to implement constructors in the code as opposed to dynamically constructing an object. Example Below:

Instead of:

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

The 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?

like image 805
Achilles Avatar asked Jan 01 '26 12:01

Achilles


2 Answers

One advantage would be that myLibObjConstructor can be reused somewhere else

like image 80
Lourens Avatar answered Jan 03 '26 01:01

Lourens


If it's existing code that already works without the need for constructors, the benefits of moving toward constructors could be marginal or non-existent.

However, the general advantages of using constructors would be:

  • Object instances have a "type" i.e. you can check instanceof or constructor to make decisions given just an object instance.
  • The most important of all, you get encapsulation. You can encapsulate "private" properties, inheritance etc., leading to cleaner and more portable code.
  • Using a constructor is more concise and more conventional than instantiating a generic object first and tacking on properties.
like image 25
Ates Goral Avatar answered Jan 03 '26 02:01

Ates Goral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!