【发布时间】:2010-03-17 12:37:40
【问题描述】:
我正在尝试获取我的班级的实例名称。
我这样做的方法是遍历所有全局对象并将其与 this 指针进行比较。
它适用于 Chrome 和 FF,但在 IE 中则不行。问题似乎是全局变量似乎不在窗口中。
如何循环浏览 IE 中的全局变量?
PS:我知道它只有在只有一个实例的情况下才有效,并且我不想将实例的名称作为参数传递。
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"
【问题讨论】:
-
您能否提供更多上下文。你为什么要这样做?
-
获取类的实例名
标签: javascript html internet-explorer