Sunday, May 1, 2011

How to get class object's name as a string in Javascript?

Let's say I instantiate an object in Javascript like this:

var myObj = new someObject();

Now, is it possible to obtain the var object's name as string 'myObj' from within one of the class methods?


Additional details (edited):

The reason why I would like to get the name of the variable holding reference to the object is that my new myObj would create a new clickable DIV on the page that would need to call a function myObj.someFunction(). As I insert the new DIV I need to know the name of the variable holding reference to the object. Is there maybe a better way of doing this?

From stackoverflow
  • Short answer: No. myObj isn't the name of the object, it's the name of a variable holding a reference to the object - you could have any number of other variables holding a reference to the same object.

    Now, if it's your program, then you make the rules: if you want to say that any given object will only be referenced by one variable, ever, and diligently enforce that in your code, then just set a property on the object with the name of the variable.

    That said, i doubt what you're asking for is actually what you really want. Maybe describe your problem in a bit more detail...?


    Pedantry: JavaScript doesn't have classes. someObject is a constructor function. Given a reference to an object, you can obtain a reference to the function that created it using the constructor property.


    In response to the additional details you've provided:

    The answer you're looking for can be found here: JavaScript Callback Scope (and in response to numerous other questions on SO - it's a common point of confusion for those new to JS). You just need to wrap the call to the object member in a closure that preserves access to the context object.

  • Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:

    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 
      } 
    }
    // 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
    // create a global variable referring to an object
    var myVar = new myClass()
    myVar.myName() // returns "myVar"
    

    Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.

    edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:

    function myConstructor () {
      this.count = 0
      this.clickme = function () {
        this.count += 1
        alert(this.count)
      }
    
      var newDiv = document.createElement("div")
      var contents = document.createTextNode("Click me!")
    
      // This is the crucial part. We don't construct an onclick handler by creating a
      // string, but instead we pass in a function that does what we want. In order to
      // refer to the object, we can't use this directly (since that will refer to the 
      // div when running event handler), but we create an anonymous function with an 
      // argument and pass this in as that argument.
      newDiv.onclick = (function (obj) { 
        return function () {
          obj.clickme()
        }
      })(this)
    
      newDiv.appendChild(contents)
      document.getElementById("frobnozzle").appendChild(newDiv)
    
    }
    window.onload = function () {
      var myVar = new myConstructor()
    }
    
    Miroslav Solanka : Passing the name of the variable to the constructor is what I have been doing so far, though was wondering whether there is perhaps a different way of achieving the same thing.
    Miroslav Solanka : Brian, thanks for the additional comments. I ended up assigning the onclick handler dynamically, as you point out in your revised answer, rather than passing it as a string in the div's onclick property.
  • You are right, sorry for the mixup in terminology.

    The reason why I would like to get the name of the variable holding reference to the object is that my new myObj would create a new clickable DIV on the page that would need to call a function myObj.someFunction(). As I insert the new DIV I need to know the name of the variable holding reference to the object. Is there maybe a better way of doing this?

    Shog9 : @Miroslav: for future reference, you should elaborate on your question by editing it - answers posted with additional details sort at the bottom and tend to get missed (also, it's not actually an answer). The answer you're looking for can be found here: http://stackoverflow.com/questions/183214/javascript-callback-scope (and in response to numerous other questions on SO - it's a common point of confusion for those new to JS)
  • You can do it converting by the constructor to a string using .toString() :

    function getObjectClass(obj){
       if (typeof obj != "object" || obj === null) return false;
       else return /(\w+)\(/.exec(obj.constructor.toString())[1];}
    
    Brian Campbell : I believe the OP was asking for the name of the variable, not the name of the constructor.
  • You might be able to achieve your goal by using it in a function, and then examining the function's source with toSource():

    var whatsMyName;
    
      // Just do something with the whatsMyName variable, no matter what
    function func() {var v = whatsMyName;}
    
    // Now that we're using whatsMyName in a function, we could get the source code of the function as a string:
    var source = func.toSource();
    
    // Then extract the variable name from the function source:
    var result = /var v = (.[^;]*)/.exec(source);
    
    alert(result[1]); // Should alert 'whatsMyName';
    

0 comments:

Post a Comment