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 Person {
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
11const Anthony = new Person('Anthony', 32);
1class Polygon {
2 constructor(height, width) {
3 this.height = height;
4 this.width = width;
5 }
6
7 get area() {
8 return this.calcArea();
9 }
10
11 calcArea() {
12 return this.height * this.width;
13 }
14}
15
16const square = new Polygon(10, 10);
17
18console.log(square.area);
1// Initializing a class definition
2class Hero {
3 constructor(name, level) {
4 this.name = name;
5 this.level = level;
6 }
7}