Section 6. OOP

Wendy·2021년 2월 18일
0

Udemy - JavaScript: The Advanced Concepts

Section 6. Object Oriented Programing

OOP & FP (Functional Programing)

JS에서는 아래 두가지 패러다임을 모두 쓸수 있다!

  • OOP : 데이터와 함수를 한 객체 안에 - prototype 기반
  • FP : 데이터와 함수를 분리 - 클로저 기반

OOP Principle

1. Factory Functions

function createElf(name, weapon) {
  return {
    name,
    weapon,
    atack : () => return 'atack with ' + weapon
  }
}

const sam = createElf('Sam', 'bow');
const peter = createElf('Peter', 'bow');

객체를 하나하나 만들지 않을수 있게 되었다.
그래도 여전히 같은 함수가 반복 저장되어 메모리 낭비가 발생ㅜㅜ

2. Obejct.create()

const elfFunctions = {
  attack: function() {
    return 'atack with ' + this.weapon
  }
}

function createElf(name, weapon) {
  let newElf = Object.create(elfFunctions)
  newElf.name = name;
  newElf.weapon = weapon
  return newElf
}

const sam = createElf('Sam', 'bow');
const peter = createElf('Peter', 'bow');

위의 문제를 해결했음. 좋긴 좋아.
그런데 이런 스타일을 그다지 볼수는 없어.(선호의 차이)
표준적인 OOP 코드 스타일이 아니어서...일까?

3. Constructor Functions

function Elf(name, weapon) {
  this.name = name;
  this.weapon = weapon;
}

Elf.prototype.attack = function() { 
  return 'atack with ' + this.weapon
}

const sam = new Elf('Sam', 'bow');
const peter = new Elf('Peter', 'bow');

Constructor 함수 방식을 사용 (Number, String과 같은...)

  • 시작은 대문자
  • this에 값을 넣어주고 new 하면, this에 담았던 것들이 객체화 되어 만들어진다

그런데 모두가 prototype에 대해 잘 알아? 해석하기 어렵지 않겠어?

4. ES6 Classes

class Elf {
  //new 할때마다 실행되어 instance별로 다른 값을 가짐
  constructor(name, weapon) {	
    this.name = name;
    this.weapon = weapon;
  }
  
  //instance들이 함께 쓰는 함수 (이걸 constructor에 넣으면 메모리낭비)
  attack() {	
    return 'atack with ' + this.weapon
  }
}

const fiona = new Elf('Fiona', 'ninja stars');

console.log(typeof Elf) //function 
console.log(typeof fiona) //object

OOP 스타일의 클래스를 적용!
하지만 사실은 클래스타입은 따로 없고 내부에서 prototype 이용해 만든것이다.

class Person {
  constructor(nickName){
    this.nickName = nickName;
  }
  familyName = 'hong';
  #givenName = "GD"; //private field 나옴 (ES2020)
}

const son = new Person("pig");

console.log(son.familyName); // hong
console.log(son.nickName); //pig
console.log(son.#givenName); //Private field... error

상속

class Character {
  constructor(name, weapon) {
    this.name = name;
    this.weapon = weapon;
  }
  attack() {
    return 'atack with ' + this.weapon
  }
}

class Elf extends Character { 
  constructor(name, weapon, type) {
    super(name, weapon) 
    this.type = type;
  }
}

const houseElf = new Elf('Dolby', 'cloth', 'house')

this의 4가지 해석방법

  1. 암시적 사용 : 호출하는 객체가 this (dynamic scope)
  2. 명시적 사용 : .bind() 로 this 지정
  3. new : 클래스의 인스턴스가 this
  4. 화살표 함수 : 선언 위치의 this (lexical scope)

읽어본 글

https://ko.javascript.info/constructor-new

profile
개발 공부중!

0개의 댓글