1class Person {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6}
7
8const person = new Person("John Doe", 23);
9
10console.log(person.name); // expected output: "John Doe"
1<script>
2 class Student {
3 constructor(rno,fname,lname){
4 this.rno = rno
5 this.fname = fname
6 this.lname = lname
7 console.log('inside constructor')
8 }
9 set rollno(newRollno){
10 console.log("inside setter")
11 this.rno = newRollno
12 }
13 }
14 let s1 = new Student(101,'Sachin','Tendulkar')
15 console.log(s1)
16 //setter is called
17 s1.rollno = 201
18 console.log(s1)
19</script>
1A constructor is a function that creates an instance of a class
2 which is typically called an “object”. In JavaScript, a constructor gets
3 called when you declare an object using the new keyword.
4 The purpose of a constructor is to create an object and set values if
5 there are any object properties present.
6
1// Improved formatting of Spotted Tailed Quoll's answer
2class Person {
3 constructor(name, age) {
4 this.name = name;
5 this.age = age;
6 }
7 introduction() {
8 return `My name is ${name} and I am ${age} years old!`;
9 }
10}
11
12let john = new Person("John Smith", 18);
13console.log(john.introduction());
1 class Cat {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6
7 get fullname() {
8 return this.getFullName()
9 }
10 getFullName() {
11 return this.name + ' ' + this.age
12 }
13 }
14
15 const run = document.getElementById("run");
16 run.addEventListener("click", function () {
17 let Skitty = new Cat('Skitty', 9);
18 let Pixel = new Cat('Pixel', 6);
19 console.log(Skitty.getFullName()); // Skitty 9
20 console.log(Skitty.fullname); // Skitty 9 => shorter syntax
21 console.log(Skitty, Pixel);
22 // Object { name: "Skitty", age: 9} Object {name: "Pixel", age:6}
23 })
1class prettyMixedGirl {
2 constructor(name, age, ethnicity, phoneNumber) {
3 this.name = name;
4 this.age = age;
5 this.ethnicity = ethnicity;
6 this.phoneNumber = phoneNumber;
7 }
8 // Method
9 hi() {
10 console.log(`Hi! My name is ${this.name}. I am ${this.age} years old. My ethnicity is ${this.ethnicity}. My phone number is ${this.phoneNumber}`);
11 }
12}
13// Create new object out of Constructor (Instantiate)
14const ashley = new prettyMixedGirl('Ashley', 28, 'Dominican Republican', '313-218-1345');
15const luna = new prettyMixedGirl('Luna', 26, 'Chilean', '718-231-1343');
16
17// Initiate a method
18ashley.hi(); // Hi! My name is Ashley. I am 28 years old. My ethnicity is Dominican Republican. My phone number is 313-218-1345
19luna.hi(); // Hi! My name is Luna. I am 26 years old. My ethnicity is Chilean. My phone number is 718-231-1343