Given:
function MyCtor() {}
var myInstance = new MyCtor(); //myInstance.constructor ==== MyCtor
var MyCtor = function() {}
var myInstance = new MyCtor(); //myInstance.constructor ==== Function
If you instantiate an object using the former pattern the constructor is "more meaningful".
Is one of these approaches preferred? Are there circumstances where one is more idiomatic?
In the first case you have a named function and thus see that name, when you stringify the constructor.
In the second case you just have a pointer to an anonymous function, hence no name can be shown for the constructor.
You can combine both, though, by using a named function for the second case:
var MyCtor = function MyCtor() {}
var myInstance = new MyCtor(); //myInstance.constructor === MyCtor
this also works:
var otherRefName = function MyCtor() {}
var myInstance = new otherRefName(); //myInstance.constructor === MyCtor
With respect to the usage:
You can use this pattern, when you need to pass around the constructor to some other function (maybe a callback).
A (very very) simplified example could be something like this:
getConstructor( type ) {
switch( type ) {
case 'a': return function ContrA(){};
case 'b': return function ContrB(){};
}
}
var myConstr = getConstructor( 'a' ),
myInstance = new myContr(); // myInstance.constructor === ConstrA
Other related questions:
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