Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-22 14:54:03
Original
280 people have browsed it

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

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

var myObject = window[classNameString];
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!