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!