Call a JavaScript class object with variable?

In JavaScript, you can call a class constructor with variables by passing the variable as an argument. There are several ways to achieve this, including direct instantiation and using eval().

Basic Class Instantiation with Variables

The most straightforward approach is to pass variables directly to the class constructor:

class FirstClass {
    constructor(message) {
        this.message = message;
    }
}

var message = 'This is the Class Demo';
var object = new FirstClass(message);
console.log(object.message);
This is the Class Demo

Using eval() with Class Objects

You can use eval() to dynamically evaluate expressions involving class objects:

class FirstClass {
    constructor(message) {
        this.message = message;
    }
}

var message = 'This is the Class Demo';
var object = new FirstClass(message);

// Using eval to access object properties
console.log(eval('object.message'));
This is the Class Demo

Dynamic Class Instantiation

For more dynamic scenarios, you can store class names in variables and instantiate them:

class FirstClass {
    constructor(message) {
        this.message = message;
    }
}

class SecondClass {
    constructor(message) {
        this.message = `Second: ${message}`;
    }
}

var className = 'FirstClass';
var message = 'Dynamic class creation';

// Using eval to instantiate class dynamically
var object = eval(`new ${className}('${message}')`);
console.log(object.message);
Dynamic class creation

Alternative Approach: Using a Class Registry

A safer alternative to eval() is using a class registry:

class FirstClass {
    constructor(message) {
        this.message = message;
    }
}

class SecondClass {
    constructor(message) {
        this.message = `Second: ${message}`;
    }
}

// Class registry
const classRegistry = {
    FirstClass,
    SecondClass
};

var className = 'FirstClass';
var message = 'Using class registry';

var object = new classRegistry[className](message);
console.log(object.message);
Using class registry

Key Points

  • Direct instantiation with variables is the most common and straightforward approach
  • eval() can be used for dynamic evaluation but should be avoided when possible due to security concerns
  • Class registries provide a safer alternative for dynamic class instantiation
  • Always ensure variables are properly defined before passing them to class constructors

Conclusion

While eval() can call JavaScript class objects with variables, direct instantiation or class registries are safer and more maintainable approaches. Choose the method that best fits your specific use case.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements