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.

4

3 回答 3

2

您需要为函数提供名称:-

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

console.log(array1[0].constructor.name)
于 2013-06-07T21:30:33.663 回答
0

在大多数浏览器中,函数都有名称,但您不使用它。所以,我们不得不求助于黑客在云中找到你的构造函数,这在 IE7 中不起作用,也许是 8:

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

如果你没有在全局范围内运行代码,这个技巧就行不通!同样,这是一个 hack,你应该找到一种更好的做事方式,比如命名你的函数,即使它们是表达式。

于 2013-06-07T21:31:29.117 回答
0

尝试实例,

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 '';

}
于 2013-06-07T21:34:26.780 回答