This isn't practically possible. Local variable names are not preserved in any semantic way in JavaScript; the language has no reflection capabilities that would let you retrieve them. It might be hypothetically possible to have a program in the right environment connect to its own debugger port to determine a local variable name, but that would extremely complicated and slow.
But as a fun exercise, here's a function which will work for the specific example you've provided. PLEASE DO NOT USE THIS FUNCTION IN REAL CODE. This code checks the name of your class (this.constructor.name
), and then searches up the call stack for any parent functions containing X = new NAME
, and returns the first X
it finds. This approach is extremely crude and unreliable, relies on the super-deprecated .caller
property, will probably hurt your application performance, won't work in strict
mode, and your coworkers will give you dirty looks.
function myFunction(x,y,z) {
this.var1 = x*y;
this.var2 = "someting else";
};
myFunction.prototype.whatismyname = function() {
// Get the name of this class's constructor.
var name = this.constructor.name;
// Start by searching in the function calling this method.
var caller = arguments.callee.caller;
var match = null;
// Search up the call stack until we find a match or give up.
while (!match && caller) {
// Get the source code of this function on the stack.
var code = caller.toString();
// Search the source code for X = new NAME.
var match = new RegExp('\\W(\\w+)\\s*=\\s*new\\s+' + name).exec(code);
// Move up the stack.
caller = caller.caller;
}
// Return the first match.
return match && match[1] || undefined;
};
function main() {
var varName = new myFunction(10,99,7);
other(varName);
}
function other(myObj) {
console.log(myObj.whatismyname()); // "varName"
}
main();
It "works"! Sort-of. In this case. Don't do it.