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
1//use classes by initiating one like so:
2class MyClass {
3 constructor(FirstProperty, SecondProperty, etcetera) {
4 //The constructor function is called with the new class
5 //instance's parameters, so this will be called like so:
6 //var classExample = new MyClass("FirstProperty's Value", ...)
7 this.firstProperty = FirstProperty;
8 this.secondProperty = SecondProperty;
9 }
10 //creat methods just like functions:
11 method(Parameters) {
12 //Code Here
13 }
14 //getters are properties that are calculated when called, versus fixed
15 //variables, but still have no parenthesis when used
16 get getBothValues()
17 {
18 return [firstProperty, secondProperty];
19 }
20}
21//Note: this is all syntax sugar reducing the boilerplate versus a
22// function-defined object.
1class Hi {
2 constructor() {
3 console.log("hi");
4 }
5 my_method(){}
6 static my_static_method() {}
7}
8
9function getMethods(cl) {
10 return Object.getOwnPropertyNames(cl.prototype)
11}
12
13console.log(getMethods(Hi)) // => [ 'constructor', 'my_method' ]
14
1
2class ClassName {
3
4 constructor() { ... }
5
6 method_1() { ... }
7
8 method_2() { ... }
9
10 method_3() { ... }
11
12}
13