Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object instantiation options

Tags:

javascript

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?

like image 695
Ben Aston Avatar asked Sep 30 '22 04:09

Ben Aston


1 Answers

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:

  • var functionName = function() {} vs function functionName() {}
like image 158
Sirko Avatar answered Oct 15 '22 11:10

Sirko