Take the 2-minute tour ×

I have a

var code = new CodeObject();

is there a way to get the name of the instance ("code" in the example) inside the CodeObject function?

something like:

function CodeObject() {
    this.id = this.instanceName;

thanks in advance

I know that in general the thing is really unpredictable, but mine is a really specific case where the constructor is always called in the way shown above.

And I would need it because I want to use the name of the instance without having to pass it to the constructor to avoid repetition of chars (the JSP file that contains the calls is too big already).

share|improve this question
Definitely not. Also, what if you did array.push(new CodeObject()) -- what would the name be then? If you want the object to have a name, then pass the name as a constructor parameter. –  Jon Nov 14 '12 at 12:46
Just curious, why would you need it? the this pointer is a reference to the object itself –  Ashwini Khare Nov 14 '12 at 12:47
That kind of introspection is not possible. –  Asad Nov 14 '12 at 12:48
A variable refers to e.g. an object, but an object is not bound to one variable. You can store it at numerous places (variables, properties), or even use it on the fly without storing it. –  pimvdb Nov 14 '12 at 12:50
@AshwiniKhare: This can be needed to pass variable name to Flash movie (since object itself cannot be passed to Flash movie) that could later use this name to call a JS function or to alter the JS variable value. –  Marat Tanalin Nov 14 '12 at 15:18

1 Answer 1

function hello() {
  var name = /function ([^\(]+)/.exec(this.constructor)[0];
share|improve this answer
This gives the arguments of the constructor. What the OP wants is the name of the variable where the instance is stored –  pimvdb Nov 14 '12 at 14:21

Your Answer


