Javascript获取类的实例名称 [英] Javascript get name of instance of class
问题描述
function myClass(a,b,c) {
this.alertMyName=function(){alert(instancename)}
{...}
}
and then
foo = myClass(a,b,c);
boo = myClass(a,b,c);
foo.alertMyName(); //it should alert 'foo'
boo.alertMyName(); //it should alert 'boo'
在实践中,我需要它为类创建很多html对象前缀他们的ID来区分它们与由该类的另一个实例创建的同一对象。
In practice I'll need it for class that is creating a lot of html objects to prefix their ID's to differentiate them from same object created by another instance of this class.
推荐答案
answer,javascript中的变量具有一个值,它是一个原始或对对象的引用。如果值是引用,那么它引用的东西不知道变量的名称是什么。
Further to David's answer, variables in javascript have a value that is either a primitive or a reference to an object. Where the value is a reference, then the thing it references has no idea what the "name" of the variable is.
请考虑:
var foo = new MyThing();
var bar = foo;
现在应该 foo.alertMyName()
return?甚至:
So now what should foo.alertMyName()
return? Or even:
(new MyThing()).alertMyName();
如果你想要实例有一个名字,然后给他们一个属性, 。
If you want instances to have a name, then give them a property and set its value to whatever suits.
这篇关于Javascript获取类的实例名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!