我正在尝试获取班级的实例名称。
我这样做的方法是遍历所有全局对象并将其与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"
答案 0 :(得分:2)
更好的主意,解决了:
function myClass_IE()
{
this.myName = function ()
{
// search through the global object for a name that resolves to this object
for (var i = 0; i < document.scripts.length; i++)
{
var src = document.scripts[i].innerHTML ;
//document.write('script ' + i + ' = ' + document.scripts[i].innerHTML )
var idents = src.replace(/\W/g, ' ').replace(/(function|if|for|while|true|false|null|typeof|var|new|try|catch|return|prototype|this)/g, '').split(' ');
for(var j = 0; j < idents.length; j++)
{
//var iden = String(idents[j]).trim();
var iden = String(idents[j]);
if (window[iden] == this)
{
// http://mcarthurgfx.com/blog/article/iterating-global-variables-in-internet-explorer
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
return iden;
}
}
}
}
}
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"
答案 1 :(得分:2)
在IE中,除非您明确将全局变量定义为窗口对象的属性,否则它不可枚举。
var noEnum = true; // won't show up in a for...in loop
window.willEnum = true; // will show up in a for...in loop
显然,您找到了自己的解决方案,但它仅适用于内联脚本 - 尽管可以使用ajax从缓存中获取内容(如果未缓存它们,则从服务器获取内容)。< / p>