"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Dynamically Instantiate JavaScript Objects Using Class Names Stored in Variables?

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

Published on 2024-11-03
Browse:909

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.

Release Statement This article is reprinted at: 1729576035 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3