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 Car {
2 constructor(brand, speed) {
3 this.brand = brand
4 this.speed = speed
5 }
6 speedUp() {
7 this.speed += 5
8 console.log(`The ${this.brand} is travelling at ${this.speed} mph`)
9 }
10 slowDown() {
11 this.speed -= 5
12 console.log(`The ${this.brand} is travelling at ${this.speed} mph`)
13
14 }
15}
16const redCar = new Car('toyota', 0)
17redCar.speedUp() // result: The toyota is travelling at 5 mph
18redCar.slowDown() // result: The toyota is travelling at 0 mph
19
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
1class MyArray extends Array {
2 // Overwrite species to the parent Array constructor
3 static get [Symbol.species]() { return Array; }
4}
5
6let a = new MyArray(1,2,3);
7let mapped = a.map(x => x * x);
8
9console.log(mapped instanceof MyArray); // false
10console.log(mapped instanceof Array); // true
11
1const Animal = {
2 speak() {
3 console.log(`${this.name} makes a noise.`);
4 }
5};
6
7class Dog {
8 constructor(name) {
9 this.name = name;
10 }
11}
12
13// If you do not do this you will get a TypeError when you invoke speak
14Object.setPrototypeOf(Dog.prototype, Animal);
15
16let d = new Dog('Mitzie');
17d.speak(); // Mitzie makes a noise.
18
1
2class ClassName {
3
4 constructor() { ... }
5
6 method_1() { ... }
7
8 method_2() { ... }
9
10 method_3() { ... }
11
12}
13