How to export default constructors ?
Last Updated :
21 Jun, 2021
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:
- Create a file index.html.
- Create a User.js file that will export the module.
- Create another Profile.js file to import the constructor and check whether it’s invoked on creating an object.
- Add script-src in index.html (Note: Since we are exporting modules we need to add type=”module”)
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.
index.html
<!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 >
|
Profile.js
import User from './User.js' ;
var user = new User({name: 'Lorem Ipsum' ,lang: 'Javascript' });
console.log(user);
|
User.js
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:
- You will see a list of the local server serving as shown below:
List of Available ports serving
- Now click on any available local server, we will see the following output.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...