TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

JavaScript OOPs Constructor Method

JavaScript OOPs Constructor Method with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, data types, operators, javascript if, switch, operators, objects, form validation, map, typedarray etc.

<< Back to JAVASCRIPT

JavaScript Constructor Method

A JavaScript constructor method is a special type of method which is used to initialize and create an object. It is called when memory is allocated for an object.

Points to remember

  • The constructor keyword is used to declare a constructor method.
  • The class can contain one constructor method only.
  • JavaScript allows us to use parent class constructor through super keyword.

Constructor Method Example

Let's see a simple example of a constructor method.

<script>
class Employee {
  constructor() {
    this.id=101;
    this.name = "Martin Roy";
  } 
}
var emp = new Employee();
document.writeln(emp.id+" "+emp.name);
</script>
Test it Now

Output:

101 Martin Roy

Constructor Method Example: super keyword

The super keyword is used to call the parent class constructor. Let's see an example.

<script>
class CompanyName
{
  constructor()
  {
    this.company="TheDeveloperBlog";
  }
}
class Employee extends CompanyName {
  constructor(id,name) {
   super();
    this.id=id;
    this.name=name;
  } 
}	
var emp = new Employee(1,"John");
document.writeln(emp.id+" "+emp.name+" "+emp.company);
</script>
Test it Now

Output:

1 John TheDeveloperBlog

Note - If we didn't specify any constructor method, JavaScript use default constructor method.

Next TopicJS static Method




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf