JavaScript Object Instance Parameters
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 previous template, the constructor is "more meaningful".
Is one of these approaches the preferred approach? Are there cases where a person is more idiomatic?
+3
source to share
2 answers
In the first case, you have a named function, and thus you see that name when you create a constructor.
In the second case, you have a pointer to an anonymous function, so no name can be specified for the constructor.
You can combine both, though, 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 regard to use:
You can use this pattern when you need to pass the constructor to some other function (perhaps 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:
+4
source to share