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']
    • Method 2 is useful to utilize dynamic properties, for example

      1
      2
      3
      4
      5
      let prop = 'name'
      user[prop]
      prop = 'email'
      user[prop]
      // In this case, user.prop will not work
  • Classes in ES6 - Blueprints

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class 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
    10
    class 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
    17
    class 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
      7
      class 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
    11
    function 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
      5
      function Admin(...args){ // get all parameters in an array
      User.apply(this, args);
      }
      Admin.prototype = Object.create(User.prototype);
      Admin.prototype.deleteUser = function(){};