Open In App

How to export default constructors ?

The export statement is used to bind one JavaScript module to others. In order to export the default constructor, we use an export statement and import module at the required place. On creating an instance of the class, the constructor of a respective class is invoked.

Syntax:



export default class ClassName{...}

In the following example, we will use the JavaScript module in another module by exporting and importing it. However, Cross origin requests are only supported for HTTPS. Therefore, we need to run our HTML file on the local server. 

Approach:



 

Project Directory: Our project directory will look like this.

Project Directory Structure

Example: The index.html file will contain src to Profile.js where the module is imported. The Profile.js file will import User.js and invoke a constructor of User.js by creating an object of class User. The User.js file will have a constructor which takes params and prints its value along with some dummy text.




<!DOCTYPE html>
  
<head>
    <script type="module" 
        src="./Profile.js">
    </script>
</head>
  
<body>
    <div style="color: green; 
                font-size: 35px; 
                margin-left: 100px;">
        Geeks for Geeks
    </div>
    <p style="color: rgb(44, 46, 44); 
                font-size: 20px; 
                margin-left: 100px;">
        Result will be displayed at console
    </p>
</body>
  
</html>




// Importing User
import User from './User.js';
  
// Creating new user object
var user = new User({name:'Lorem Ipsum',lang:'Javascript'});
  
// Printing data
console.log(user);




export default class User
{
    constructor(params)
    {
        this.name=params.name;
        this.lang=params.lang;
        console.log('constructor of User class called: ');
        console.log(this.name+' is your name.');
        console.log(this.lang+' is your language');
    }
}

Steps to run HTML files on the local server

Output:


Article Tags :