如何获取对象名称

How to get object name?

本文关键字:取对象 何获      更新时间:2023-09-26

是否可以在javascript中输出对象的名称?在下面的脚本中,我将window对象传递给函数并输出属性。

var Output = "";
function OutputAttributes(pObject)
{
    var x = "";
    for (var Attribute in pObject)
    {
        x = x + "<li>"+pObject+"." + Attribute + ": " + pObject[Attribute] + "</li>";
    }
    return x;
}
Output = OutputAttributes(window);
document.write("<h2>Attributes from Objekt <i> <'/i><'/h2>");
document.write("<ol>"+Output+"</ol>");

如果我执行上面的代码,那么我会收到这样的输出:

[object Window].close: function close() { [native code] } 
[object Window].stop: function stop() { [native code] } 
[object Window].focus:function focus() { [native code] }

但我期待这样的事情:

window.focus:function focus() { [native code] }

这在 JavaScript 中是不可能的,因为这种语言中的参数是通过值或引用传递的,而不是按名称传递的,所以当变量传递给函数时,它的名字会丢失。

<script>
var str ="[object Window].focus:function focus() { [native code] }";
str = str.replace("[object","");
strlast=str.replace("Window]","Window");
alert(strlast);
</script>