TIL: Today I Learned

[TIL] 20201214 Prototypes, Classes & OOP

김알리 2020. 12. 14. 14:13

Object Prototypes

  • The mechanism by which JavaScript Object inherit features from one another.
  • A template object
  • Typically contains properties and methods.
  • __proto__ : reference to the object prototype
  • Obj.prototype : The real object prototype.

 

 

Factory Functions

  • A function that creates an object like a template.
  • If the object contains all the properties that a function needs as arguments, it's better to make that function a method of the object. Then the function doesn't need those arguments.
  • Creates a unique copy of the methods each time it creates an object. (Not reusing the methods)
  • Example
function makeColor(r, g, b) {
    const color = {}; //make an empty object
    color.r = r;
    color.g = g;
    color.b = b;
    color.rgb = function() {
        const {r, g, b} = this;
        return `rgb(${r}, ${g}, ${b})`
    };
    return color;
}

 

 

new Operator

  1. Creates a blank, plain JavaScript object.
  2. Links (sets the constructor of) this object to another object.
  3. Passes the newly created object from step1 as the this context.
  4. Returns this if the function doesn't return its own object.
  • Example
function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
}

new Color(26, 33, 153);

 

 

 

Constructor Functions

  • Functions that can create an object with new operator. (Creates the prototype)
  • More efficient than factory functions.
  • To add a method to the prototype, it should be created outside of the constructor function.
    • For example : Color.prototype.rgb = function() { //code };

 

 

JavaScript Class

  • A even better way of creating an object template.
  • Don't have to manually add methods to prototypes.
  • Syntax
class ClassName{
    constructor(x) {
        //runs immediately when a new instance is instantiabed.
        //make a new empty object and sets the values.
        this.x = x;
    }
    
    func() {
        const {x} = this; // destructure the properties
        //code
    }

}

 

 

 

Extends 

  • Inherits another class (its constructor, methods...)
  • If a method is redefined in the child class, the child class method will run.
  • Syntax
class ClassName extends ParentClass {}

 

 

 

Super

  • References the class that we're extending from.
  • Syntax
class ClassName extends ParentClass {

    constructor (x, y, z) {
        super (x, y); //references parent class
        this.z = z;
    }

}

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.