1class ClassMates{
2 constructor(name,age){
3 this.name=name;
4 this.age=age;
5 }
6 displayInfo(){
7 return this.name + "is " + this.age + " years old!";
8 }
9}
10
11let classmate = new ClassMates("Mike Will",15);
12classmate.displayInfo(); // result: Mike Will is 15 years old!
1class Person {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6 present = () => { //or present(){
7 console.log(`Hi! i'm ${this.name} and i'm ${this.age} years old`)
8 }
9}
10let me = new Person("tsuy", 15);
11me.present();
12// -> Hi! i'm tsuy and i'm 15 years old.
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());
1class Rectangle {
2 constructor(height, width) {
3 this.height = height;
4 this.width = width;
5 }
6 // Getter
7 get area() {
8 return this.calcArea();
9 }
10 // Method
11 calcArea() {
12 return this.height * this.width;
13 }
14}
15
16const square = new Rectangle(10, 10);
17
18console.log(square.area); // 100
1function Animal (name) {
2 this.name = name;
3}
4
5Animal.prototype.speak = function () {
6 console.log(`${this.name} makes a noise.`);
7}
8
9class Dog extends Animal {
10 speak() {
11 console.log(`${this.name} barks.`);
12 }
13}
14
15let d = new Dog('Mitzie');
16d.speak(); // Mitzie barks.
17
18// For similar methods, the child's method takes precedence over parent's method
19