Constructor Function:
A constructor function is a special type of function in JavaScript, which helps create new objects (data structures) with different prototypes.
It is an old syntax, used before the introduction of "class" syntax in JavaScript (ES6, 2016).
It also allows to add methods and properties in the prototype of the newly created object (data structure)
"Constructor function" and "function constructor" are completely different things,
function Person (person_name, person_age, person_gender) {
this.name = person_name,
this.age = person_age,
this.gender = person_gender,
this.greet = function () {
return ('Hi' + ' ' + this.name);
}
}
Person.prototype.getUserName = function(name){
return this.name
}
const person1 = new Person('yash', 30, "Male")
person1
"Class"
In ES6, 2015, "class" was introduced as a new way for defining Objects, instead of "constructor functions",
To create a new class, we have the "class" keyword declaration with a name (starting with Uppercase)
We can also use the "class" expression to create a new class
class User {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hi ${this.name}`);
}
}
// Usage:
let user1 = new User("John");
user1.sayHi(); // Hi John
let user2 = new User("Doe");
user2.sayHi(); // Hi Doe