-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path65 Classes.html
91 lines (83 loc) · 3 KB
/
65 Classes.html
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
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classes in Javascript</title>
</head>
<body>
<script>
/*
ECMAScript 2015, also known as ES6, introduced JavaScript Classes.
JavaScript Classes are templates for JavaScript Objects.
->JavaScript Class Syntax:
Use the keyword class to create a class.
Always add a method named constructor(){...}
Syntax:
class ClassName {
constructor() { ... }
}
*/
//example
class car{ //class name car
constructor(name,model){
this.name=name;
this.model=model;
}
//The class has two initial properties: "name" and "modal".
}
//A JavaScript class is not an object. It is a template for JavaScript objects.
//creating objects of class car
const car1=new car("Ford",2019);
const car2=new car("BMW",2023);
//The constructor method is called automatically when a new object is created.
console.log(car1.name);
console.log(car2.name," and ",car2.model)
/* important
->The Constructor Method
The constructor method is a special method:
It has to have the exact name "constructor"
It is executed automatically when a new object is created
It is used to initialize object properties
If you do not define a constructor method, JavaScript will add an empty constructor method.
*/
//we can have many class methods
//example
//add a method that returns bike age
class bike{
constructor(name,model){
this.name=name;
this.model=model;
}
//class methods
bikeAge(){
const date=new Date();
return date.getFullYear() - this.model;
}
//You can send parameters to Class methods:
bikeColor(color){
console.log("Bike Color is: ",color)
}
}
const myBike=new bike("BMW",2015);
console.log(myBike.bikeAge());
myBike.bikeColor("Blue and Gray");
//IMPORTANT:
/*
->Hoisting:
Unlike functions, and other JavaScript declarations, class declarations are not hoisted.
That means that you must declare a class before you can use it:
//You cannot use the class yet.
//myCar = new Car("Ford") will raise an error.
class Car {
constructor(brand) {
this.carname = brand;
}
}
//Now you can use the class:
const myCar = new Car("Ford")
*/
//Note: For other declarations, like functions, you will NOT get an error when you try to use it before it is declared, because the default behavior of JavaScript declarations are hoisting (moving the declaration to the top).
</script>
</body>
</html>