Javascript get name of instance of class

前端 未结 3 1959
佛祖请我去吃肉
佛祖请我去吃肉 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:09

    Further to David's answer, variables in javascript have a value that is either a primitive or a reference to an object. Where the value is a reference, then the thing it references has no idea what the "name" of the variable is.

    Consider:

    var foo = new MyThing();
    var bar = foo;
    

    So now what should foo.alertMyName() return? Or even:

    (new MyThing()).alertMyName();
    

    If you want instances to have a name, then give them a property and set its value to whatever suits.

    0 讨论(0)
  • 2020-12-12 05:23

    You could bring it in as a parameter:

    function myClass(name, a, b, c) {
       this.alertMyName = function(){ alert(name) }
    }
    
    foo = new myClass('foo', a, b, c);
    

    Or assign it afterwards:

    function myClass(a, b, c) {
       this.setName = function(name) {
           this.name = name;
       }
       this.alertMyName = function(){ 
           alert(this.name)
       }
    }
    
    foo = new myClass( a,b,c);
    foo.setName('foo');
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题