Reputation: 11299
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
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:
instanceof
or constructor
to make decisions given just an object instance.Upvotes: 1
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
Reputation: 1518
One advantage would be that myLibObjConstructor can be reused somewhere else
Upvotes: 2