How to Get the Name of an Instance of a Class in Javascript

I was using JSONP (note that I prefer CORS but this was a special case where CORS wasn’t possible) and wanted an object that needed to call a method within itself. As you know, JSONP involves adding a script tag to the DOM which will return the JSON data encapsulated in a function call. But in this case, I needed the function call to be a method of the class doing the JSONP call. So, it would be preferred to know what the instance name was. Here’s a method of finding the name of an instance of a class:

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"