1

Say, I have 2 constructors assigned to 2 variables:

var example1 = function(argument1){
    this.argument1 = argument1;
}

var example2 = function(argument2){
    this.argument2 = argument2;
}

And an array of objects containing objects from both of these constructors:

var array1 = new Array();
array1[0] = new example1(example);
array1[1] = new example2(example);

My question is, when I choose an item from the array, how can I print the name of the constructor variable it came from?

To make this clear and succint, here's an example:

console.log(array1[0].argument1)

Will print example. But I don't want that. I want it to print the name of the constructor variable it came from.

console.log(array1[0].constructor.toString());

Prints the content of the variable, but it is unsatisfactory.

  • You could use function declarations, which created named function (with a `.name` property). Not sure if standard and/or cross-browser though. checking... – Šime Vidas Jun 07 '13 at 21:28
  • Your functions don't have *names* -- they are contained inside of variables. A function could be contained inside of multiple variables, e.g., `foo = bar = function() { }`, so it's not possible to find a canonical variable that contains a function. You can, however, gives names to your functions like `function example1() { }` which is accessible with the `name` property. – apsillers Jun 07 '13 at 21:30
  • maybe duplicated of http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript – fmodos Jun 07 '13 at 21:34
  • @fmodos That question refers to a type, not to a name. – Cathedral Zealot Jun 07 '13 at 21:35

3 Answers3

2

You need to provide a name to a function:-

var example1 = function example1(argument1){
    this.argument1 = argument1;
}
 var array1 = new Array();
array1[0] = new example1({});

console.log(array1[0].constructor.name)
pvnarula
  • 2,771
  • 18
  • 22
0

in most browsers, functions have a name, but you don't use it. so, we have to resort to hacks to find your constructor in the cloud, which won't work in IE7, maybe 8:

console.log(Object.keys(self).filter(function(a){
     return self[a]===array1[0].constructor;
})[0]);

if you didn't have the code running in the global scope, this trick won't work! again, this is a hack and you should find a better way of doing things, like naming your functions, even if they are expressions.

dandavis
  • 16,370
  • 5
  • 40
  • 36
0

Try instance of,

var example1 = function(argument1){
    this.argument1 = argument1;
}

var example2 = function(argument2){
    this.argument2 = argument2;
}

console.log(getName(array1[0]));

function getName(value) {

    if (value instanceof example1) return 'example1';
    if (value instanceof example2) return 'example2';

    return '';

}
Ceres
  • 3,524
  • 3
  • 18
  • 25