-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_class.js
79 lines (65 loc) · 2.45 KB
/
1_class.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
// Class
// What
// - A class in JavaScript is a blueprint for creating objects.
// - It encapsulates data and behavior(methods) that objects created from the class will share.
// - Classes were introduced in ECMAScript 6(ES6) to provide a cleaner and more intuitive way to create and manage objects and their relationships.
// Why
// - Organization: They help organize code by grouping related data and behavior.
// - Reusability: Code can be reused more effectively by creating multiple objects from the same class.
// - Inheritance: They allow for inheritance, where one class can extend another and inherit its properties and methods.
// - Encapsulation: They help encapsulate and hide the complexity of data and behavior within a class.
// Syntax
// 1. Creating class using `class` keyword
class MyClass {
constructor(parameter1, parameter2) {
this.parameter1 = parameter1;
this.parameter2 = parameter2;
}
method() {
console.log(`We are ${this.parameter1} & ${this.parameter2}`);
console.log("I am method");
}
}
const instanceObject = new MyClass("argument1", "argument2");
console.log(instanceObject.method());
// 2. Creating class with class expression
const variable = class {
constructor() {}
};
// Example
class User {
constructor(username, email, password) {
this.username = username;
this.email = email;
this.password = password;
}
encryptPassword() {
return `${this.password}abc`;
}
changeUsername() {
return `${this.username.toUpperCase()}`;
}
}
const userOne = new User("userOne", "userone@abc.com", "123");
console.log(userOne.encryptPassword());
console.log(userOne.changeUsername());
// Behind the Scene
function CreateUser(username, email, password) {
this.username = username;
this.email = email;
this.password = password;
}
CreateUser.prototype.encryptPassword = function () {
return `${this.password}abc`;
};
CreateUser.prototype.changeUsername = function () {
return `${this.username.toUpperCase()}`;
};
const user = new CreateUser("user", "user@abc.com", "123");
console.log(user.encryptPassword());
console.log(user.changeUsername());
// Note
// - Class in JavaScript doesn't work like other programming language. It's just a syntactic sugar which look like we are using class but in the background it is using Constructor Function and Prototype Inheritance.
// - Always add a method named constructor();
// - Class can't be hoisted.
// - Class are first class citizen just like first class function.