3

in my.js

$(document).ready(function(){
    a = new person();
    b = new person();
        ...
})

person.prototype.init = function(){..}

function person(){
    var someVariable;
    function doSomeThing(){
        ...
        // I need my instance name
        ...
    }
    return {doSomeThing:doSomeThing}
}

how can I get my instance name?

soredive
  • 795
  • 1
  • 9
  • 25
  • 1
    http://stackoverflow.com/questions/789675/how-to-get-class-objects-name-as-a-string-in-javascript – Kai Jun 18 '11 at 07:57

1 Answers1

3

There's no general solution.

Objects have no intrinsic knowledge of the out-of-scope variable names to which they've been assigned.

If your variables are in global scope (which they shouldn't be) it's do-able, but only by iterating over the keys in window and finding any whose value matches this.

FWIW (unless you're writing a JS debugger) if you think you need to know this you're probably doing it wrong. JS minifiers for example often change variable names, so you shouldn't rely on them.

Alnitak
  • 334,560
  • 70
  • 407
  • 495