How can I pass in a class name as a variable using javascript?
Let's say I have the class Person.
I want to pass in the name of the class to a function so that that function can call that class.
so the function is
function openClass(name)
I want to pass in
openClass('person')
so that openClass can call the class person
for example
function openClass(name)
{
return new name() // here I want this line to actually
// call the class "Person" if that is
// what is passed in as a name parameter,
}
Answer : Yes we can have it.
To declare a variable within a class, it needs to be a property of the class or, as you did so, scoped within a method in the class. It's all about scoping and variables are not supported in the scope definition of a class.
The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter. Names can also begin with $ and _ (but we will not use it in this tutorial).
"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.
Technically, there are no classes in JavaScript. Although many third party libraries do create a class system on top of JavaScript.
The "class" is typically a constructor function. So if you have the name of the function, it's a matter of digging it out of the global scope. Assuming the function is defined globally:
var Constructor = window[name];
return new Constructor();
If your function is actually defined at say my.namespace.Person
, then it's a bit more complicated, but still the same general idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With