Home  >  Article  >  Web Front-end  >  How to Dynamically Instantiate JavaScript Objects Using Class Names Stored in Variables?

How to Dynamically Instantiate JavaScript Objects Using Class Names Stored in Variables?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 14:54:03284browse

How to Dynamically Instantiate JavaScript Objects Using Class Names Stored in Variables?

Instantiating JavaScript Objects Using Dynamic Class Names

Suppose you have a situation where you need to instantiate JavaScript objects using class names stored in variables. Here's an illustrative example:

// Define the class
MyClass = Class.extend({});

// Store the class name in a string
var classNameString = 'MyClass';

// Instantiate the object using the class name string
var myObject = new classNameString();

This approach, however, does not work. To achieve the desired behavior, you can use the following alternative:

var myObject = window[classNameString];

This approach works because the window object contains a reference to the global scope, which includes the defined classes. By accessing the class name stored in classNameString as a property of window, you can dynamically retrieve and instantiate the class.

The above is the detailed content of How to Dynamically Instantiate JavaScript Objects Using Class Names Stored in Variables?. 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