Achilles
Achilles

Reputation: 11299

What advantages are gained by using constructors in 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?

Upvotes: 3

Views: 1315

Answers (3)

Ateş Göral
Ateş Göral

Reputation: 140050

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.

Upvotes: 1

matchew
matchew

Reputation: 19645

In other words, your question boils down to prototype vs constructors. which is a great question and a lot has been written about it. Including here.

How to "properly" create a custom object in JavaScript?

Advantages of using prototype, vs defining methods straight in the constructor?

also good reading here: http://mckoss.com/jscript/object.htm

Upvotes: 0

Lourens
Lourens

Reputation: 1518

One advantage would be that myLibObjConstructor can be reused somewhere else

Upvotes: 2

Related Questions