Understanding Constructors in Python

  • Introduction to Constructors:
  • A constructor in JavaScript is a special method used to create and initialize objects within a class. It's called automatically when you create a new instance of a class. Constructors typically set initial values for object properties or perform any necessary setup tasks.

    Here's a basic example:

    JavaScript code
    <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> class Person { constructor(name, age) { this.name = name; this.age = age; } } // Creating a new instance of Person let person1 = new Person('John', 30); let person2 = new Person('Alice', 25); document.write(person1.name); // Output: John document.write(person2.age); // Output: 25 </script> </body> </html>
  • Examples :
  • JavaScript code
    Write a program with the following specification:
    Class name : factorial Data members : int a Member functions: factorial() : default constructor to initialize the data member. Void input(int m) : to assign a with m Void display() : to print factorial of the number. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> var i; class factorial { constructor() { this.a=0; } input(m) { this.a=m; this.f=1; for(i=1;i<=this.a;i++) { this.f=this.f*i; } } display() { document.write(this.f); } } ob= new factorial(); n=parseInt(prompt("Enter the no : ")); ob.input(n); ob.display(); </script> </body> </html>

    Output : Enter the no : 5
    120

    JavaScript code
    # Write a program with the following specifications:
    Class name: hcflcm Data members: int a,b Member Functions: hcflcm(int x,int y): constructor to initialize a=x and b=y Void calculate() : to find and print hcf and lcm of both the numbers. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script type="text/javascript"> var i; class hcflcm { constructor(x,y) { this.a=x; this.b=y; } calculate() { this.m=this.a * this.b; for(i=1;i<=this.m;i++) { if(this.a%i==0 && this.b%i==0) { this.h=i; } } this.l=(this.m/this.h); document.write("HCF="+this.h); document.write("<br>"); document.write("LCM="+this.l); } } n=parseInt(prompt("Enter the 1st no")); p=parseInt(prompt("Enter the 2nd no")); ob= new hcflcm(n,p); ob.calculate(); </script> </body> </html>

    Output : Enter the 1st no : 10
    Enter the 2nd no : 15
    HCF=5
    LCM=30

  • Conclusion :
  • Constructors in JavaScript play a crucial role in object-oriented programming, allowing developers to create and initialize objects with specific properties and methods. Overall, constructors are essential for structuring JavaScript applications, enabling efficient object creation and encapsulating related functionality. This promotes better organization, maintainability, and scalability in JavaScript codebases.