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

How to Create JavaScript Objects with Variable Class Names?

Mary-Kate Olsen
Release: 2024-10-22 15:40:03
Original
951 people have browsed it

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];
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template