Reputation: 131
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.
Upvotes: 1
Views: 1849
Reputation: 3658
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 '';
}
Upvotes: -1
Reputation: 16726
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.
Upvotes: 0
Reputation: 2831
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)
Upvotes: 3