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?


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() {}

  • 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 )
    
    链接地址: http://www.djcxy.com/p/96292.html

    上一篇: JavaScript的; 通过分配给变量创建的函数?

    下一篇: JavaScript对象实例化选项