Object Oriented JavaScript
Notes for https://www.youtube.com/watch?v=4l3bTDlT6ZI
Access object’s properties
1
2
3
4// Method 1
user.email
// Method 2
user['email']Classes in ES6 - Blueprints
1
2
3
4
5
6
7
8
9
10
11
12class User {
constructor(email, name) {
this.email = email;
this.name = name;
}
}
// the 'new' keyword
// - creates a new empty object {}
// - sets the value of 'this' to the new empty object
// - calls the constructor method
const userOne = new User('yoshi@gmail.com', 'Yoshi');Class methods
1
2
3
4
5
6
7
8
9
10class User {
constructor(email, name) {
this.email = email;
this.name = name;
} // no comma here
login() {
console.log(this.email, 'logged in');
}
}
userOne.login();Method chaining
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class User {
constructor(email, name) {
this.email = email;
this.name = name;
this.score = 0;
} // no comma here
login() {
console.log(this.email, 'logged in!');
return this; // chain methods
}
updateScore() {
this.score++;
return this; // chain methods
}
}
userOne.login().updateScore().updateScore().logout();Class inheritance
If create users as admins, who has methods as regular users, but also has methods specific to admins
1
2
3
4
5
6
7class Admin extends User {
deleteUser(user) {
users = users.filter((u) => u.email !== user.email);
}
}
const users = [userOne, userTwo];
Prototype model
1
2
3
4
5
6
7
8
9
10
11function User(email, name) {
this.email = email;
this.name = name;
this.online = false;
}
User.prototype.login = function(){
this.online = true;
console.log(this.email, 'has logged in!');
}
const userOne = new User('email', 'Yoshi');Prototype inheritance
To create an admin constructor function
1
2
3
4
5function Admin(...args){ // get all parameters in an array
User.apply(this, args);
}
Admin.prototype = Object.create(User.prototype);
Admin.prototype.deleteUser = function(){};