Difference Between Constructors and Function in Classes in JavaScript.
In JavaScript, constructors are special functions that are used to create and initialize objects that are created from a class. Constructors are invoked automatically when a new object is created using the new
keyword.
When using classes in JavaScript, there are a few differences between constructors and other methods:
Name: Constructors have to have the same name as the class they belong to, whereas other methods can have any name.
Execution: Constructors are executed automatically when a new object is created using the
new
keyword, whereas other methods need to be called explicitly on an instance of the class.Return value: Constructors do not return a value explicitly, whereas other methods can return any value.
Purpose: Constructors are used to set the initial state of an object, whereas other methods are used to define additional behavior or functionality for the object.
Here's an example to illustrate the differences:
javascriptCopy codeclass Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log("Hello, my name is " + this.name + " and I'm " + this.age + " years old.");
}
calculateBirthYear() {
return new Date().getFullYear() - this.age;
}
}
In this example, the Person
class has a constructor method that sets the name
and age
properties of the object. The class also has two additional methods: sayHello
and calculateBirthYear
.
The sayHello
method logs a greeting to the console, whereas the calculateBirthYear
method returns the birth year of the person based on their age.
The sayHello
method is not executed automatically when a new object is created; instead, it needs to be called explicitly on an instance of the class:
csharpCopy codevar john = new Person("John", 30);
john.sayHello(); // logs "Hello, my name is John and I'm 30 years old."
The calculateBirthYear
method also needs to be called explicitly on an instance of the class, but it returns a value that can be used in other parts of the code:
javascriptCopy codevar john = new Person("John", 30);
var birthYear = john.calculateBirthYear();
console.log("John was born in " + birthYear); // logs "John was born in 1991"
In summary, constructors are used to create and initialize objects when they are created, whereas other methods are used to define additional behavior or functionality for the object. Constructors are executed automatically when a new object is created, whereas other methods need to be called explicitly on an instance of the class.