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?

1

3 Answers 3

2

One advantage would be that myLibObjConstructor can be reused somewhere else

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

1 Comment

That's also a pretty huge advantage, and one of the most basic principles of good programming.
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.

Comments

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

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.