Call a JavaScript class object with variable?


Let’s say the following is our variable −

var message = 'This is the Class Demo';

Following is our object,

var object = new FirstClass(message)

The class FirstClass −

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

We will use eval() to call a JavaScript class object with variable. Following is the code −

Example

class FirstClass{
   constructor( message){
      this.message = message;
   }
}
var message = 'This is the Class Demo';
var object = new FirstClass(message)
console.log(eval(object).message);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo121.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo121.js
This is the Class Demo

Updated on: 09-Sep-2020

969 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements