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?
One advantage would be that myLibObjConstructor can be reused somewhere else
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With