How do I instantiate a class in CoffeeScript when I only have the name of the class in a string?
class Dog
bark:->
"Woof"
className = "Dog"
dog = new className # <--- I would like to create an instance here using the string
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
With a bit of foresight you can do this pretty easily and protect yourself against using
eval. Keep a list somewhere of the classes that you want to instantiate by name:and then use your lookup table instead of
eval:When you say
class Dog, you end up with a local variable calledDog:and there’s no way to get at a local JavaScript variable unless you store it somewhere that you can access by name. Also note that
evalwon’t work if you defineDogin one CoffeeScript file and want to access it another, CoffeeScript wraps each file in self-executing anonymous function to limit variable scope: