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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The OP initialises the instances without var so their "names" are global.
@RobG true, although of course that's bad practise. I'll clarify.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.