ovnia
ovnia

Reputation: 2500

Get name of instance of a class within the class

Here is what I want:

var Validator = function () {
   this.do = function () {
      alert(INTANCENAME); /// SHOULD BE 'FOO'
   }
}
var FOO = new Validator().do();

Is it possibe to implement in Javascript?

Upvotes: 3

Views: 103

Answers (3)

Joel Cox
Joel Cox

Reputation: 3469

There's no way to directly do what you're asking for here. Objects themselves are not in any defined by their matching variable name - in fact it's possible to have objects that exist that are not directly assigned to a variable, and multiple variables assigned to the same object.

The javascript interpreter uses our variable names as identifiers to help with the code execution, but once it's running the variable name makes no difference to the running javascript program, as it's probably been reduced to a memory reference by the time it's executing, completely separated from the original code that you wrote.

Edit: Answer by yannis does kind of simulate this, but it relies on working with variables available in a specific scope - what I ment was that there's no direct way to do this from within the object itself as per your example in the question.

Upvotes: 1

giannis christofakis
giannis christofakis

Reputation: 8321

The truth is there is no point of doing that, the only way I can hardly think is to loop all window or scope objects and check some kind of equality with the current object, something like

this.do = function () {
    for(var key in window) {
        if(this === window[key]) {
           alert(key);
        }
    }
};

In order to work call it after you assign it.

var FOO = new Validator();
FOO.do();

Another issue that can come up is that an instance (a reference) can be stored in various variables so maybe will not get what you expect.

Upvotes: 3

Andrey Shchekin
Andrey Shchekin

Reputation: 21609

The literal answer to your question would be:

  1. Use (new Error()).stack to get information on the line and the function where the do() method was called.
  2. Use JS parser (e.g. Esprima) to find out what variable it was called on (if any, the method itself might be assigned to a variable).

I do not recommend doing this though.

Upvotes: 2

Related Questions