Creating JavaScript Objects with Variable Class Names
You're attempting to create a JavaScript object using a variable string to define the class name. Here's an adjusted version of your code that should work:
// Define the class var MyClass = class { }; // Store the class name in a variable var classNameString = 'MyClass'; // Instantiate the object var myObject = new window[classNameString];
The adjustment is made in the object instantiation line, where we use the window[classNameString] notation to access the class object dynamically. This works because JavaScript classes are assigned to the global window object when defined.
However, note that this approach requires the class to be defined before creating the object. If you want to create an object before defining its class, you'll need to use a different approach, such as dynamically evaluating the code that defines the class based on the variable string.
The above is the detailed content of How to Create JavaScript Objects with Variable Class Names?. For more information, please follow other related articles on the PHP Chinese website!