-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathes6_4_classes.js
83 lines (70 loc) · 1.54 KB
/
es6_4_classes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* ES6/ES2015
* Classes
* JavaScript classes are syntactic sugar over existing prototype based inheritance.
* @author Mahmud Ahsan
* {@link https://github.com/mahmudahsan/javascript}
*/
/**
* constructor is a special method to initialize class object while initiating.
*/
class Address {
constructor(city, country){
this.city = city;
this.country = country;
}
print(){
console.log(this.city);
console.log(this.country);
}
}
// initiating instance of class
const myAddress = new Address('dhaka', 'bangladesh');
myAddress.print();
/**
* static method
* can be called with the class name
*/
class Point {
constructor(x, y){
this.x = x;
this.y = y;
}
static distance(pointA, pointB){
const ptX = Math.pow((pointB.x - pointA.x), 2);
const ptY = Math.pow((pointB.y - pointA.y), 2);
const dt = Math.sqrt(ptX + ptY);
return dt;
}
}
const pt1 = new Point(5, 2);
const pt2 = new Point(10, 3);
const distanceOfPt = Point.distance(pt1, pt2);
console.log(distanceOfPt);
/**
* Subclass
*/
class Car {
constructor(brand, type){
this.brand = brand;
this.type = type;
}
print(){
console.log('Brand: ' + this.brand);
console.log('Type: ' + this.type);
}
}
// if subclass has constructor it needs to call
// super before using this
class Honda extends Car {
constructor(brand, type, model){
super(brand, type);
this.model = model;
}
print(){
super.print();
console.log('Model: ' + this.model);
}
}
const honda = new Honda('honda', 'sedan', 'accord');
honda.print();