Home  >  Article  >  Web Front-end  >  How to Create JavaScript Objects with Variable Class Names?

How to Create JavaScript Objects with Variable Class Names?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 15:40:03856browse

How to Create JavaScript Objects with Variable Class Names?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn