![](https://s3.amazonaws.com/media-p.slid.es/uploads/2591572/images/11082663/11.png)
Class in JavaScript
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2591572/images/11082667/15.png)
Constructor Functions
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
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2591572/images/11082667/15.png)
Classes in JavaScript
"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
Class in JavaScript
By Yash Priyam
Class in JavaScript
- 87