Ben Aston
Ben Aston

Reputation: 55729

JavaScript object instantiation options

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?

Upvotes: 5

Views: 173

Answers (2)

Royi Namir
Royi Namir

Reputation: 148524

As an addition ( and a bit off) to @sirko's answer , I will add the hoisting POV :

var myInstance = new MyCtor();
function MyCtor() {}
alert(myInstance.constructor ) //MyCtor

while

var myInstance = new MyCtor();  //error
var MyCtor = function() {}
alert(myInstance.constructor )

Upvotes: 0

Sirko
Sirko

Reputation: 74046

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:

Upvotes: 4

Related Questions