3

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?

Achilles
  • 11,165
  • 9
  • 62
  • 113
  • good question! but possible dupe of http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor and http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript – matchew Jun 09 '11 at 14:33

3 Answers3

2

One advantage would be that myLibObjConstructor can be reused somewhere else

Lourens
  • 1,510
  • 1
  • 13
  • 27
  • That's also a pretty huge advantage, and one of the most basic principles of good programming. – Svend Jun 09 '11 at 14:32
1

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.
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
0

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

Community
  • 1
  • 1
matchew
  • 19,195
  • 5
  • 44
  • 48