Javascript获取类实例的名称

Ada*_*chy 1 javascript class

function myClass(a,b,c) {
     this.alertMyName=function(){alert(instancename)}

{...}


}
Run Code Online (Sandbox Code Playgroud)

然后

foo = myClass(a,b,c);
boo = myClass(a,b,c);

foo.alertMyName(); //it should alert 'foo'
boo.alertMyName(); //it should alert 'boo'
Run Code Online (Sandbox Code Playgroud)

在实践中,我需要它来创建许多html对象的类,以便为它们的ID添加前缀,以便将它们与该类的另一个实例创建的同一对象区分开来.

Kme*_*ner 6

我无法在Stack Overflow上找到解决方案,所以这里是我在dforge.net上从ronaldcs 找到的解决方案:http://www.dforge.net/2013/01/27/how-to-get-the-name- 一个类的实例在javascript /

myObject = function () {
  this.getName = 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;
  };
};
Run Code Online (Sandbox Code Playgroud)

试试看:

var o = new myObject(); 
alert(o.getName()); // alerts "o"
Run Code Online (Sandbox Code Playgroud)

  • 我很惊讶这个答案没有得到足够的重视。 (2认同)