howtoweb howtoweb - 1 year ago 87
Javascript Question

Get name of constructor in javascript

Is there a way to get the name of the variable made with a constructor?

var TestFunction = function () { = ???(); // should return '$testName'
var $testName = new TestFunction();

should return


Answer Source

should return '$testName'

That means you're asking how a function can know the name of a variable its result (or rather, the result of new calling it) is about to be assigned to. It can't, there is no mechanism for that, not least because of these possibilities:

a = b = c = d = new TestFunction();
// or
new TestFunction();
// or
foo(new TestFunction());

...but really because fundamentally, the function has no business knowing anything about the context in which it's called other than what the programmer has chosen to tell it by passing as arguments.

Consequently, if you want the function to have that information, you'll need to pass it in, even though that's repetitive:

var $testName = new TestFunction("$testName");

There's a special case (variables at global scope) where you could avoid repeating the name and only pass it as an argument to the function (leaving off the var $testname = part) and then have the function create the "variable," but it would tie the function to global scope, which would fall deep, deep into Bad Idea™ territory. :-)

This is what the special case looks like. Strongly recommend not doing this. (Instead: squint had an excellent suggestion in a comment.)

function TestFunction(name) {
    window[name] = this; // Creates a global =name;

new TestFunction("$testname");
console.log($testname); // {name: "$testname"}

That works because when you create a property on the global object (which you can access via window on browsers), it creates a global variable.

Please don't do that. :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download