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.
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