Javascript get name of instance of class

前端 未结 3 1958
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 04:44
function myClass(a,b,c) {
     this.alertMyName=function(){alert(instancename)}

{...}


}

and then

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


        
3条回答
  •  囚心锁ツ
    2020-12-12 05:28

    I Couldn't find a solution on Stack Overflow so here is a solution I found from ronaldcs on dforge.net: http://www.dforge.net/2013/01/27/how-to-get-the-name-of-an-instance-of-a-class-in-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;
      };
    };
    

    Try it Out:

    var o = new myObject(); 
    alert(o.getName()); // alerts "o"
    

提交回复
热议问题