본문 바로가기
Web Development/JavaScript

29. Prototypes, Classes, & OOP

by 사향낭 2022. 1. 15.

 

295. Prototype

 

JavaScript is a prototype-based language to provide inheritance.

 

Objects can have a prototype object, which acts as a template object that it inherits methods and properties from.

 

prototype: a property of a class constructor

__proto__: a property of a class instance

 

 

297. Factory function

 

The function which returns an object.

 

It makes function property of the instance whenever instance is created.

 

function makeColor(r, g, b) {
    const color = {};
    color.r = r;
    color.g = g;
    color.b = b;
    color.rgb = function () {
        const { r, g, b } = this;
        return `rgb(${r}, ${g}, ${b})`;
    }
    return color;
}

const color = makeColor(100, 255, 30);
console.log(color);
/*
{r: 100, g: 255, b: 30, rgb: ƒ}
 b: 30
 g: 255
 r: 100
 rgb: ƒ ()
 [[Prototype]]: Object
*/

 

 

298. Constructor function

 

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
}

Color.prototype.rgb = function () {
    const { r, g, b } = this;
    return `rgb(${r}, ${g}, ${b})`;
}

const color = new Color(100, 255, 30);
console.log(color);
/*
Color {r: 100, g: 255, b: 30}
 b: 30
 g: 255
 r: 100
 [[Prototype]]: Object
  rgb: ƒ ()
  constructor: ƒ Color(r, g, b)
  [[Prototype]]: Object
*/

 

 

299. JavaScript Class

 

class Color {
    constructor(r, g, b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    rgb() {
        const { r, g, b } = this;
        return `rgb(${r}, ${g}, ${b})`;
    }
}

const color = new Color(100, 255, 30);
console.log(color);
/*
Color {r: 100, g: 255, b: 30}
 b: 30
 g: 255
 r: 100
 [[Prototype]]: Object
  constructor: class Color
  rgb: ƒ rgb()
  [[Prototype]]: Object
*/

 

 

301. Extends and Super Keywords

 

class Pet {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    eat() {
        return `${this.name} is eating!`;
    }
}

class Cat extends Pet {
    constructor(name, age, livesLeft = 9) {
        super(name, age);
        this.livesLeft = livesLeft;
    }

    meow() {
        return 'MEOWWWW!!';
    }
}

class Dog extends Pet {
    bark() {
        return 'WOOOF!!';
    }
}

 

'Web Development > JavaScript' 카테고리의 다른 글

28. AJAX and API's  (0) 2022.01.05
27. Async JavaScript  (0) 2022.01.04

댓글