howtoweb howtoweb - 13 days ago 5
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 () {
this.name = ???(); // should return '$testName'
}
var $testName = new TestFunction();


$testName.name
should return
$testName

THX

Answer

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.)

// STRONGLY RECOMMEND NOT DOING THIS
function TestFunction(name) {
    window[name] = this; // Creates a global
    this.name =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. :-)

Comments