我试图获取我的类的实例名称。
我这样做的方式是循环遍历所有全局对象并将其与此指针进行比较。
它在Chrome和FF中工作,但在IE中,它没有。这个问题似乎是全球变量似乎并不在窗口中。
如何循环浏览IE中的全局变量?
PS:我知道它只在只有一个实例时才起作用,而且我不想将实例的名称作为参数传递。JavaScript:在IE中列出全局变量
function myClass()
{
this.myName = function()
{
// search through the global object for a name that resolves to this object
for (var name in this.global)
{
if (this.global[name] == this)
return name
}
}
}
function myClass_chrome()
{
this.myName = function()
{
// search through the global object for a name that resolves to this object
for (var name in window)
{
if (window[name] == this)
return name ;
}
} ;
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
//myClass_IE.prototype.global = this
// create a global variable referring to an object
// var myVar = new myClass()
var myVar = new myClass_chrome()
//var myVar = new myClass_IE()
alert(myVar.myName());// returns "myVar"
你能否提供更多的上下文。你为什么做这个? – Cheeso 2010-03-17 12:42:58
获取类的实例名称 – 2010-03-17 13:02:47